Python ssh模塊
python有很多第三方的SSh模塊弄屡,我們也可以使用python自帶的ssh模塊,進(jìn)行一些常用的操作
Code: 1. 文件上傳拖陆,下載抹恳,命令執(zhí)行
#!/usr/bin/env python
# -*-coding:utf-8-*-
import ssh
__author__ = "Allen Woo"
def connect_host(ip, port, username, password):
'''
連接遠(yuǎn)程主機(jī)
'''
client = ssh.SSHClient()
client.set_missing_host_key_policy(ssh.AutoAddPolicy())
try:
client.connect(ip, port = port,
username = username,
password = password)
except Exception,e:
print e
return False
return client
# 連接遠(yuǎn)程服務(wù)器
client = connect_host(192.168.1.111, 22, "test", "123456")
# 文件下載
sftp = client.open_sftp()
remote_file = "/home/work/test.txt"
local_save_path = "/home/work/temp_file/text.txt"
sftp.get(remote_file, local_save_path)
# 文件上傳差不多
remote_save_path = "/home/work/upload/test.txt"
local_file = "/home/work/text.txt"
sftp.put(local_file, remote_save_path)
# 命令執(zhí)行
stdin, stdout, stderr = client.exec_command("ls -l ")
r = stdout.read()
print(r)
Code: 2. 獲取遠(yuǎn)程服務(wù)器的目錄list
def sftp_walkdir(sftp, path):
'''
遞歸獲取path下的所有文件與目錄
:param sftp: python ssh sftp object
:param path:
:return:
'''
now_dirname = os.path.split(path)[-1]
backups = []
files = sftp.listdir_attr(path)
for f in files:
tpath = "{}/{}".format(path, f.filename)
if f.longname[0] == "d":
r = sftp_walkdir(sftp, tpath)
backups.append(r)
else:
backups.append({"filename":f.filename, "_path_":tpath})
return {now_dirname:backups, "_path_":path}
# 測(cè)試下
# 連接遠(yuǎn)程服務(wù)器
client = connect_host(192.168.1.111, 22, "test", "123456")
r = sftp_walkdir(sftp, "/home/work/sshtest")
print(json.dumps(r, sort_keys=True, indent=2))
看下Code2 目錄list的結(jié)果
{
"_path_": "/home/work/sshtest",
"sshtest": [
{
"_path_": "/home/work/sshtest/test2.txt",
"filename": "test2.txt"
},
{
"_path_": "/home/work/sshtest/test1.txt",
"filename": "test1.txt"
},
{
"_path_": "/home/work/sshtest/sshtest_222",
"sshtest_222": [
{
"_path_": "/home/work/sshtest/sshtest_222/test_lalalal.txt",
"filename": "test_lalalal.txt"
},
{
"_path_": "/home/work/sshtest/sshtest_222/sshtest_333_222",
"sshtest_333_222": [
{
"_path_": "/home/work/sshtest/sshtest_222/sshtest_333_222/test_ooooo.txt",
"filename": "test_ooooo.txt"
}
]
},
{
"_path_": "/home/work/sshtest/sshtest_222/sshtest_333",
"sshtest_333": []
},
{
"_path_": "/home/work/sshtest/sshtest_222/test_hahahah.txt",
"filename": "test_hahahah.txt"
}
]
}
]
}