一、paramiko是基于Python實(shí)現(xiàn)的SSH2遠(yuǎn)程安裝連接,支持認(rèn)證及密鑰方式橡类。可以實(shí)現(xiàn)遠(yuǎn)程命令執(zhí)行窝爪,文件傳輸弛车,中間SSH代理等功能。
import paramiko
ip = 'x.x.x.x'
port = 22
ssh_username = 'root'
ssh_password = 'xxxxxx'
command = 'uptime'
ssh_user_connect = paramiko.SSHClient() #實(shí)例化SSHClient
ssh_user_connect.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #自動(dòng)添加策略
ssh_user_connect.connect(ip,port,ssh_username,ssh_password,timeout=10) #連接SSH服務(wù)端蒲每,以用戶名帅韧、密碼進(jìn)行認(rèn)證
stdiin,stdout,stderr = ssh_user_connect.exec_command(command) #打開一個(gè)channel并執(zhí)行命令
result = stdout.read().decode('utf-8')
print(result)
二、fabric是基于Python實(shí)現(xiàn)的SSH命令行工具啃勉,簡(jiǎn)化了SSH的應(yīng)用程序部署及系統(tǒng)管理任務(wù),它提供了系統(tǒng)基礎(chǔ)的操作組件双妨,可以實(shí)現(xiàn)本地或遠(yuǎn)程shell命令淮阐,包括命令執(zhí)行,文件上傳刁品,下載及完整執(zhí)行日志輸出等功能泣特。Fabric在paramiko的基礎(chǔ)上做了更高一層的封裝,操作起來更加簡(jiǎn)單挑随。
- 簡(jiǎn)單的例子状您,對(duì)遠(yuǎn)程服務(wù)器進(jìn)行操作
from fabric import Connection
host_ip = 'x.x.x.x'
user_name = 'root'
port = 22
password = 'xxxxxx'
cmd = 'date'
conn = Connection(host_ip,user_name,port,connect_kwargs={'password':password}) #建立連接
result = conn.run(cmd,hide=True) #執(zhí)行命令,hide=True表示隱藏輸出
print(result.stdout) #打印結(jié)果
- 命令行用法
#文件名:fabfile.py
from fabric import Connection
from fabric import task
host_ip = 'x.x.x.x'
user_name = 'root'
port = 22
password = 'xxxxxx'
cmd = 'date'
@task
def test1(c):
'''
Get ip date remote host
'''
conn = Connection(host_ip,user_name,port,connect_kwargs={'password':password})
conn.get('/etc/passwd','') #拉取遠(yuǎn)端文件到本地兜挨,第二個(gè)參數(shù)為空時(shí)使用默認(rèn)路徑膏孟。
#用推送本地文件到遠(yuǎn)端文件系統(tǒng)用put();get()方法的默認(rèn)存儲(chǔ)路徑是os.getcwd,put()方法的默認(rèn)存儲(chǔ)路徑是home目錄。
然后在該腳本同級(jí)目錄的CMD命令行窗口中拌汇,可以查看和執(zhí)行相應(yīng)的任務(wù):
>fab -l
Available tasks:
test1 Get date from remote host.
>fab test1
- 批量操作
ip_file = r'D:\ip.txt'
with open(ip_file) as f:
ip_content = f.readlines() #讀取文件內(nèi)容柒桑,保存到一個(gè)列表中
for ip in ip_content:
result = Connection(ip.rstrip(),'root',22,connect_kwargs={'password':'xxxxxx'}).run('df -h',hide=True) #ip.rstrip()刪除ip后面的空行
print(result.stdout)