本文整理汇总了Python中smb.SMBConnection.SMBConnection.close方法的典型用法代码示例。如果您正苦于以下问题:Python SMBConnection.close方法的具体用法?Python SMBConnection.close怎么用?Python SMBConnection.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smb.SMBConnection.SMBConnection
的用法示例。
在下文中一共展示了SMBConnection.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SambaHelper
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
class SambaHelper():
def __init__(self, user, password, serverName):
self.__username = user
self.__password = password
self.__connect(serverName)
def __connect(self, serverName):
self.conn = SMBConnection(self.__username, self.__password, '','',use_ntlm_v2 = True)
self.conn.connect(serverName, 139)
print "Connected."
def CopyFileToSambaShare(self, fileName, shareName):
file_obj=file(fileName, 'r')
print file_obj.name
self.conn.storeFile(shareName, '/{0}'.format(fileName), file_obj)
def CopyFilesToSambaShare(self, inputDir, shareName):
files = os.listdir(inputDir)
for file in files:
if file.endswith('.jpg'):
print file
self.CopyFileTo("{0}/{1}".format(inputDir,file), shareName)
def CloseConnection():
self.conn.close()
示例2: run_brute_force
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def run_brute_force(username, password, args):
ip = args.ip
port = args.port
domain = args.domain
list_shares = args.list_shares
timeout = args.timeout
verbose = args.verbose
client_name = "client"
server_name = ip
if port == 445:
is_direct_tcp = True
else:
is_direct_tcp = False
try:
# def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False)
conn = SMBConnection(username, password, client_name, server_name, domain = domain, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp)
smb_authentication_successful = conn.connect(ip, port, timeout = timeout)
if smb_authentication_successful:
print "success: [%s:%s]" % (username, password)
if list_shares:
list_smb_shares(conn, timeout)
else:
if verbose:
print "failed: [%s:%s]" % (username, password)
except:
if verbose:
e = sys.exc_info()
print "%s" % str(e)
finally:
if conn:
conn.close()
示例3: smb_scan
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def smb_scan(ip, port, list_shares, timeout, verbose):
# empty username and password for null session
username = ""
password = ""
client_name = "client"
server_name = ip
if port == 445:
is_direct_tcp = True
else:
is_direct_tcp = False
try:
# def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False)
conn = SMBConnection(username, password, client_name, server_name, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp)
smb_authentication_successful = conn.connect(ip, port, timeout = timeout)
if smb_authentication_successful:
print "SMB active [null session enabled]: %s:%s" % (ip, port)
if list_shares:
list_smb_shares(conn, timeout)
else:
# on Windows 7 authentication fails due to disabled null sessions
print "SMB active [null session disabled]: %s:%s" % (ip, port)
except:
if verbose:
e = sys.exc_info()
print "%s" % str(e)
finally:
if conn:
conn.close()
示例4: show_dir
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def show_dir(path):
conn = SMBConnection(USERNAME, PASSWORD, MY_NAME, REMOTE_NAME, use_ntlm_v2=False)
conn.connect(SERVER_IP, PORT)
re = conn.listPath('Share', os.path.join('/ESAP/Hand-Out/', path))
conn.close()
for i in re:
i.link = os.path.join(path, i.filename)
return render_template('hello.html', files=re)
示例5: dotransform
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def dotransform(args):
mt = MaltegoTransform()
# mt.debug(pprint(args))
mt.parseArguments(args)
ip = mt.getVar("ip")
port = mt.getVar("port")
hostid = mt.getVar("hostid")
server = mt.getVar("server")
if not server:
server = mt.getVar("machinename")
workgroup = mt.getVar("workgroup")
path = mt.getVar("path")
domaindns = mt.getVar("domain_dns")
sharename = mt.getVar("sharename")
if not workgroup:
workgroup = "WORKGROUP"
# conn = SMBConnection('', '', "localhost", server, domain=workgroup, use_ntlm_v2=True,is_direct_tcp=True)
conn = SMBConnection('', '', "localhost", server, domain=workgroup, use_ntlm_v2=True)
conn.connect(ip, int(port))
regex = re.compile("^\.{1,2}$")
try:
files = conn.listPath(sharename, path)
except NotReadyError:
accessdenied = mt.addEntity("msploitego.AccessDenied",sharename)
accessdenied.setValue(sharename)
else:
for file in files:
filename = unicodedata.normalize("NFKD", file.filename).encode('ascii', 'ignore')
if file.isDirectory:
if not regex.match(filename):
entityname = "msploitego.SambaShare"
newpath = "{}/{}".format(path,filename)
else:
continue
else:
entityname = "msploitego.SambaFile"
newpath = "{}/{}".format(path, filename)
sambaentity = mt.addEntity(entityname,"{}/{}{}".format(ip,sharename,newpath))
sambaentity.setValue("{}/{}{}".format(ip,sharename,newpath))
sambaentity.addAdditionalFields("ip", "IP Address", False, ip)
sambaentity.addAdditionalFields("port", "Port", False, port)
sambaentity.addAdditionalFields("server", "Server", False, server)
sambaentity.addAdditionalFields("workgroup", "Workgroup", False, workgroup)
sambaentity.addAdditionalFields("filename", "Filename", False, filename)
sambaentity.addAdditionalFields("path", "Path", False, newpath)
sambaentity.addAdditionalFields("hostid", "Hostid", False, hostid)
if domaindns:
sambaentity.addAdditionalFields("domain_dns", "Domain DNS", False, domaindns)
sambaentity.addAdditionalFields("sharename", "Share Name", False, sharename)
conn.close()
mt.returnOutput()
mt.addUIMessage("completed!")
示例6: getFileList
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def getFileList():
filename_list = []
conn = SMBConnection(smb_credential['user'], smb_credential['password'], "", smb_credential['hostname'], use_ntlm_v2 = True)
conn.connect(smb_credential['host'], 139)
file_list = conn.listPath(short_group_name, u'/Audit/每周会议记录/%s-%s年%s学期会议记录' % (short_group_name, cur_year, cur_semester))
for f in file_list:
if f.filename != '.' and f.filename != '..':
filename_list.append(f.filename)
conn.close()
return filename_list
示例7: show_file
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def show_file(filename):
conn = SMBConnection(USERNAME, PASSWORD, MY_NAME, REMOTE_NAME, use_ntlm_v2=False)
conn.connect(SERVER_IP, PORT)
#This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files). See the description of file objects for operations (section File Objects). (For standard strings, see str and unicode.)
temp_fh = StringIO()
#file_obj A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service. In Python3, this file-like object must have a write method which accepts a bytes parameter.
file_attributes, filesize = conn.retrieveFile('Share', '/ESAP/Hand-Out/' + filename, temp_fh)
conn.close()
#读取文件名字
localfile = filename.split('/')[-1]
#存到服务器
f = open(os.path.join(os.getcwd() + '/static/', localfile), 'w')
f.write(temp_fh.getvalue())
#读取服务器的文件
return redirect(url_for('static', filename=localfile), code=301)
示例8: login
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def login(worker):
finished=False
conn=SMBConnection(userID, passwords[worker], 'client_machine_name', server_name, use_ntlm_v2 = True)
while not finished:
try:
if conn.connect(server_ip, 139,timeout=100):
rightPass=password[worker]
conn.close()
finished=True
except Exception as e:
if "An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full" in str(e):
finished=False
time.sleep(1)
else:
print(e)
del conn
示例9: run
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def run(self):
print "Starting thread for " + self.ip
net = NetBIOS()
net_name = str(net.queryIPForName(self.ip)).strip("['").strip("']")
net.close()
conn = SMBConnection(self.user, self.pwd, 'cobwebs', net_name, domain=self.domain, use_ntlm_v2 = False)
if conn.connect(self.ip, port=139, timeout=10):
print ("Connecting to %s was successful! How about a nice game of spidering %s%s?" % (self.ip, self.share, self.subfolder))
else:
print ("Connection error: %s" % (self.ip))
if self.recursive > 0:
recurse(conn,self.ip,self.share,self.subfolder,self.pattern,int(self.recursive))
else:
filelist = conn.listPath(self.share, self.subfolder)
dir_list(filelist,self.ip,self.subfolder,self.pattern)
conn.close()
print "Exiting thread for " + self.ip
示例10: main
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def main():
parser = argparse.ArgumentParser('check_smbproxy')
parser.add_argument('server_ip', metavar='server-ip')
parser.add_argument('server_port', metavar='server-port', type=int)
parser.add_argument('server_name', metavar='server-name')
parser.add_argument('share_name', metavar='share-name')
parser.add_argument('--path', default='/')
parser.add_argument('--user', default='cluster_user')
parser.add_argument('--password', default='cluster_user_password')
parsed_args = parser.parse_args()
userID = parsed_args.user
password = parsed_args.password
client_machine_name = 'test_client'
server_ip = parsed_args.server_ip
server_port = parsed_args.server_port
server_name = parsed_args.server_name
share_name = parsed_args.share_name
path = parsed_args.path
try:
start_time = datetime.datetime.utcnow()
conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2=False, is_direct_tcp=True)
assert conn.connect(server_ip, server_port)
ls = conn.listPath(share_name, path)
num_files = len(ls)
# for f in ls:
# print f.filename
conn.close()
end_time = datetime.datetime.utcnow()
time_spent = (end_time-start_time).total_seconds()*1000
print "OK: %d files found in %s | connection_time=%dms" % (num_files, path, time_spent)
except Exception:
print "CRITICAL: Exception while trying to connect:"
print traceback.print_exc()
sys.exit(2)
sys.exit(0)
示例11: test_smb
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def test_smb(ip, port, credentials):
success = []
nb = NetBIOS.NetBIOS(broadcast=False)
try:
# names = nb.queryIPForName(ip,139,timeout=10)
# if names == None or names == []:
# name = ""
# else:
# name = names[0]
for login in credentials:
password = credentials[login]
conn = SMBConnection(login, password, "PwnieXpress", "")
result = conn.connect(ip,port=port,timeout=30)
if result:
success.append([login,password])
conn.close()
except Exception as e:
print(e)
nb.close()
return success
示例12: check_ip
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def check_ip(ip):
global timeout, verbose, user, password, domain, print_lock, debug
try:
# Connect to socket
conn = SMBConnection(user, password, "detect_unsecure_admin_share.py", ip, domain=domain, use_ntlm_v2=True, is_direct_tcp=True)
assert conn.connect(ip, 445, timeout=timeout)
if debug:
with print_lock:
print("#DEBUG: Successfully connected to ip: {}".format(ip))
f = tempfile.TemporaryFile()
f.write("Hello World!\n")
try:
conn.storeFile("C$", "detect_unsecure_admin_share.tmp", f, timeout=timeout)
with print_lock:
print("#SUCCESS: Successfully stored test file on C$ admin share at ip: {}".format(ip))
conn.deleteFiles("C$", "detect_unsecure_admin_share.tmp", timeout=timeout)
if debug:
with print_lock:
print("#DEBUG: Successfully deleted test file from C$ admin share at ip: {}".format(ip))
except Exception as ex:
if debug:
with print_lock:
print("#ERROR: Could not store file on C$ admin share on ip: {}".format(ip))
finally:
conn.close()
f.close()
except socket.timeout:
if debug:
with print_lock:
print("#DEBUG: Connection timed out for ip: {}".format(ip))
except Exception as ex:
if debug:
with print_lock:
print("#DEBUG: Connection failure for ip: {}".format(ip))
示例13: __init__
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
class smb_connector:
def __init__(self, ip, shared_directory, username, password):
self.connection = SMBConnection(username, password, "this_machine", "remote_machine", use_ntlm_v2=True, is_direct_tcp=True)
self.connection.connect(ip, 445)
self.shared_directory = shared_directory
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
self.connection.close()
def file_contents(self, path):
with tempfile.NamedTemporaryFile() as file_obj:
self.connection.retrieveFile(self.shared_directory, path, file_obj)
file_obj.seek(0)
content = file_obj.read().decode('utf-8', 'ignore').translate({ord('\u0000'): None})
return content
def all_files_recursively(self, full_path, file_filter, directory_filter, relative_path=''):
whats_here = self.connection.listPath(self.shared_directory, full_path)
for file in whats_here:
file_path = os.path.join(full_path, file.filename)
file_relative_path = os.path.join(relative_path, file.filename)
if file.isDirectory:
if directory_filter(file.filename) and '.' not in file.filename:
yield from self.all_files_recursively(file_path, file_filter, directory_filter, file_relative_path)
elif file_filter(file.filename):
yield os.path.normpath(file_relative_path)
def write_file(self, path, contents):
with tempfile.NamedTemporaryFile() as file_obj:
bytes = file_obj.write(contents.encode('utf-8'))
file_obj.seek(0)
bytes = self.connection.storeFile(self.shared_directory, path, file_obj)
示例14: startProtocol
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def startProtocol(port, user, passwd, ip, regex, target_path, args):
global mirror, verbose, timeout
mirror = args.search
verbose = args.verbose
timeout = args.timeout
serverName = '*'
conn = []
direct = True
if port != '445':
serverName = input("SMB over TCP is used by default on port 445.\nIf you prefer NetBIOS instead, you need to provide the NetBIOS name of the remote machine: ")
direct = False
try:
conn = SMBConnection(user, passwd, 'noone', serverName, use_ntlm_v2 = True, is_direct_tcp = direct)
stdout.write("Trying SMB server: %s......" % str(ip))
stdout.flush()
conn.connect(str(ip), int(port), timeout = timeout)
print("[Connected]")
shares(target_path, conn, regex)
conn.close()
except OSError as err:
print("[No connection]")
if verbose > 0: print(err.message)
conn.close()
pass
示例15: getNetworkShares
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import close [as 别名]
def getNetworkShares(self, hostip, hostname):
sharelist = []
self.sharecache_file = None
self.sharecache_file = eEnv.resolve("${sysconfdir}/enigma2/") + hostname.strip() + '.cache' #Path to cache directory
username = "guest"
password = ""
if os_path.exists(self.sharecache_file):
print '[Networkbrowser] Loading userinfo from ',self.sharecache_file
try:
self.hostdata = load_cache(self.sharecache_file)
username = self.hostdata['username']
password = self.hostdata['password']
except:
pass
for port in (445, 139):
try:
smbconn = SMBConnection(username, password, self._myhostname, hostname, is_direct_tcp=(port == 445))
if smbconn.connect(hostip, port=port, timeout=1):
print '[Networkbrowser] established SMB connection to %s:%d' % (hostip, port)
for share in smbconn.listShares(timeout=1):
if share.type == SharedDevice.DISK_TREE and not share.isSpecial:
sharelist.append( NetworkItemSmb(hostname, hostip, share.name.encode('utf-8'), 'Disk', comment=share.comments.encode('utf-8')) )
smbconn.close()
break
except Exception as e:
Log.w('[Networkbrowser] SMBConnection: ' + str(e))
try:
exports = showmount(hostip)
except IOError as e:
Log.w('[Networkbrowser] showmount: ' + str(e))
else:
for ex in exports:
sharelist.append( NetworkItemNfs(os_path.basename(ex['dir']), hostip, ex['dir'], ','.join(ex['groups'])) )
return sharelist