importparamiko
class
sshconnection:
#初始化連線建立transport通道
def__init__
(self, host, user, pwd):
self.host =host
self.port = 22self.user =user
self.pwd =pwd
self.
__transport =paramiko.transport((self.host, self.port))
self.
__transport.connect(username=self.user, password=self.pwd)
self.sftp = paramiko.sftpclient.from_transport(self.__transport
)
#關閉通道
defclose(self):
self.sftp.close()
self.
__transport
.close()
#上傳檔案到遠端主機
defupload(self, local_path, remote_path):
self.sftp.put(local_path, remote_path)
#def
download(self, local_path, remote_path):
self.sftp.get(remote_path, local_path)
#在遠端主機上建立目錄
def mkdir(self, target_path, mode='
0777'):
self.sftp.mkdir(target_path, mode)
#刪除遠端主機上的目錄
defrmdir(self, target_path):
self.sftp.rmdir(target_path)
#檢視目錄下檔案以及子目錄(如果需要更加細粒度的檔案資訊建議使用listdir_attr)
deflistdir(self, target_path):
return
self.sftp.listdir(target_path)
#刪除檔案
defremove(self, target_path):
self.sftp.remove(target_path)
#檢視目錄下檔案以及子目錄的詳細資訊(包含內容和參考os.stat返回乙個fstpattributes物件,物件的具體屬性請用__dict__檢視)
deflistdirattr(self, target_path):
try:
list =self.sftp.listdir_attr(target_path)
except
baseexception as e:
(e) list =
return
list
#獲取檔案詳情
defstat(self, remote_path):
return
self.sftp.stat(remote_path)
#sshclient輸入命令遠端操作主機
defcmd(self, command):
ssh =paramiko.sshclient()
ssh.set_missing_host_key_policy(paramiko.autoaddpolicy)
#設定以什麼方式連線遠端客戶端,這裡配置自動協商
ssh._transport = self.__transport
stdin, stdout, stderr = ssh.exec_command(command) #
遠端執行命令,結果會返回標準輸入、標準輸出、標準錯誤輸出
result =stdout.read()
(result)
return result
具體使用舉例:
from paramikotools importsshconnection
import
osimport
time
import
datetime
from cmdline import
parse_args
from util_log import
logging
ssh =none
logging =logging().get_logger()
#遞迴遍歷遠端目錄下的所有檔案
defgci(remote_path,pathlist):
for f in
ssh.listdirattr(remote_path):
if (str(f.longname).split("
")[0].startswith('d'
)): gci(os.path.join(remote_path,f.filename),pathlist)
else
:
return
pathlist if
__name__ == '
__main__':
#接收引數
args =parse_args()
#初始化ssh
ssh = sshconnection(host=args.srchost,user=args.srcuser,pwd=args.srcpasswd)
while
true:
try:
#建立本地接收檔案目錄(按天建立目錄)
datedir = os.path.join(args.dstpath,datetime.datetime.now().strftime('
%y%m%d'))
#建立子目錄之前保證父級目錄建立否則丟擲異常
os.mkdir(args.dstpath)
os.mkdir(datedir)
except
baseexception as e:
pass
beforedict =dict()
afterdict =dict()
pathlist =
#獲取所有檔名以及每個檔案的當前大小
for i in
gci(args.srcpath,pathlist):
beforedict.setdefault(i,ssh.stat(i).st_size)
#隔interval秒獲取每個檔名以及當前大小
time.sleep(int(args.interval))
for i in
gci(args.srcpath,pathlist):
afterdict.setdefault(i,ssh.stat(i).st_size)
#for i in
beforedict.keys():
if beforedict.get(i) ==afterdict.get(i):
try:
ssh.download(os.path.join(datedir,os.path.basename(i)),i)
logging.info(
'file
'+i+'
download completed')
ssh.remove(i)
logging.info(
'file
'+i+'
deleted')
except
baseexception as e:
logging.error(
'file
'+i+'
download failed')
logging.error(e)
logging.error(
'file
'+i+'
delete failed')
ssh.close()
參考:
Python 模組paramiko簡單使用方法
python模組paramiko可以實現用ssh登入伺服器,並執行shell usr bin python importsys importparamiko defpycmd server,port,username,password,shellcmd ssh paramiko.sshclient ...
paramiko 模組安裝
windows版本 需要的軟體包 pycrypto ecdsa paramiko 1 pycrypto的安裝自己下一步機可以了。2 安裝ecdsa,直接用cmd進入ecdsa目錄下,輸入 python setup.py install 3 安裝paramiko,和ecdsa一樣,進入paramiko...
paramiko 模組安裝
windows版本 所需軟體有 pycrypto ecdsa paramiko。二 安裝步驟 1 pycrypto的安裝自己下一步機可以了。2 安裝ecdsa,直接用cmd進入ecdsa目錄下,輸入 python setup.py install 3 安裝paramiko,和ecdsa一樣,進入pa...