paramiko模塊提供了ssh及sft進(jìn)行遠(yuǎn)程登錄服務(wù)器執(zhí)行命令和上傳下載文件的功能。這是一個(gè)第三方的軟件包,使用之前需要安裝。
創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),特克斯企業(yè)網(wǎng)站建設(shè),特克斯品牌網(wǎng)站建設(shè),網(wǎng)站定制,特克斯網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷,網(wǎng)絡(luò)優(yōu)化,特克斯網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
import paramiko
# ssh root@ip
# 創(chuàng)建一個(gè)ssh對(duì)象
client = paramiko.SSHClient()
#如果第一次連接陌生的IP,自動(dòng)選擇yes確認(rèn)連接
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接服務(wù)器
client.connect(hostname='111.231.215.66',port=22,username='手動(dòng)屏蔽帳號(hào)',password='手動(dòng)屏蔽密碼')
# 執(zhí)行操作
stdin,stdout,stderr = client.exec_command('hostname')
# 獲取命令執(zhí)行結(jié)果
host = stdout.read().decode('utf-8').strip()
print(host)
while True:
command = input("[root@%s]# " %host)
if command == 'exit()':
break
else:
r = client.exec_command(command)[1].read().decode('utf-8')
print(r)
# 關(guān)閉連接
client.close()
例子1:
連接文件 主機(jī)信息.txt 中的所有主機(jī)
不能連接返回連接失敗,成功連接,返回其主機(jī)名
把連接情況寫入文件。
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def ssh_info(ip,port=22,user='root',passwd='westos'):
try:
client.connect(hostname=ip,port=port,username=user,password=passwd)
r = client.exec_command('hostname')[1].read().decode('utf-8')
except:
print('連接失敗......')
return '連接失敗......'
else:
client.close()
print('連接成功......','\n主機(jī)名:%s' %r)
return '連接成功......'+'\n主機(jī)名:%s' %r
with open('連接狀況.txt','w') as f,open('主機(jī)信息.txt') as p:
for line in p:
line = line.strip()
ip, port, user, passwd = line.split(':')
s = ' 正在連接%s '.center(30, '+') % ip
f.write(s+'\n')
f.write(ssh_info(ip,port,user,passwd)+'\n')
例子2:
基于公鑰私鑰的批量連接
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def ssh_info(ip,pkey,port=22,user='root'):
try:
print(' 正在連接%s '.center(30, '+') % ip)
client.connect(hostname=ip,port=port,username=user,pkey=pkey)
r = client.exec_command('hostname')[1].read().decode('utf-8')
except:
print('連接失敗......')
else:
client.close()
print('連接成功......','\n主機(jī)名:%s' %r)
pkey = paramiko.RSAKey.from_private_key_file('id_rsa')
for i in range(254):
ip = '172.25.254.'+str(i+1)
ssh_info(ip,pkey)
例子3:
基于公鑰私鑰的上傳下載
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
transport = paramiko.Transport(('172.25.254.39', 22))
transport.connect(username='root',pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)
#上川下載
sftp.put('/tmp/kiosk', '/mnt/kiosk2')
sftp.get('/mnt/kiosk2', '/home/kiosk/Desktop/day18/kiosk')
transport.close()
paramiko綜合練習(xí)實(shí)例1
import os
import paramiko
group = [file.rstrip('.conf') for file in os.listdir('host')]
print('主機(jī)組'.center(30,'+'))
for i,g in enumerate(group):
print('\t',str(i+1),'\t',g)
choice = input('選擇操作組:')
print('主機(jī)'.center(30,'+'))
host_info_list = [] # 存儲(chǔ)文件中主機(jī)信息
file = 'host/'+choice+'.conf'
with open(file) as f:
for line in f:
line =line.split(':')
print('\t',line[0])
host_info_list.append(line)
def do_cmd(cmd,hostname,port=22, username='root', password='westos'):
print('連接主機(jī) ',hostname)
try:
client.connect(hostname, port, username, password)
stdin, stdout, stderr = client.exec_command(cmd)
result = stdout.read().decode('utf-8').strip()
except:
print('連接失敗......')
else:
client.close()
print(result)
def get_put(cmd,hostname,port=22, username='root', password='westos'):
print('連接主機(jī) ', hostname)
try:
transport = paramiko.Transport((hostname, int(port)))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
except:
print('連接失敗......')
else:
# 上川下載
if cmd[0] == 'put':
sftp.put(cmd[1], cmd[2])
print('上傳成功......')
elif cmd[0] == 'get':
sftp.get(cmd[1], cmd[2])
print('下載成功......')
else:
print('暫時(shí)沒有這個(gè)命令的操作......',cmd[0])
transport.close()
while True:
cmd = input('>>>: ')
cmd = cmd.split()
if cmd == []:
continue
elif len(cmd) == 1:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for host in host_info_list:
do_cmd(cmd[0],host[0],host[1],host[2],host[3])
else:
for host in host_info_list:
get_put(cmd,host[0],host[1],host[2],host[3])
paramiko封裝實(shí)例1:
import os
import paramiko
class SSH_host:
def __init__(self,ip,port,u,p,cmd):
self.ip = ip
self.port = port
self.username = u
self.passwd = p
self.cmd = cmd
def cmd(self):
print('連接主機(jī) ',self.ip)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(self.ip, self.port, self.username, self.passwd)
stdin, stdout, stderr = client.exec_command(self.cmd[0])
result = stdout.read().decode('utf-8').strip()
except:
print('連接失敗......')
else:
print(result)
client.close()
def get(self):
print('連接主機(jī) ', self.ip)
try:
transport = paramiko.Transport((self.ip, self.port))
transport.connect(self.username, self.passwd)
sftp = paramiko.SFTPClient.from_transport(transport)
except:
print('連接失敗......')
else:
sftp.get(self.cmd[1], self.cmd[2])
print('下載成功......')
transport.close()
def put(self):
print('連接主機(jī) ', self.ip)
try:
transport = paramiko.Transport((self.ip, self.port))
transport.connect(self.username, self.passwd)
sftp = paramiko.SFTPClient.from_transport(transport)
except:
print('連接失敗......')
else:
sftp.put(self.cmd[1], self.cmd[2])
print('上傳成功......')
transport.close()
if __name__ == "__main__":
group = [file.rstrip('.conf') for file in os.listdir('host')]
print('主機(jī)組'.center(30,'+'))
for i,g in enumerate(group):
print('\t',str(i+1),'\t',g)
choice = input('選擇操作組:')
print('主機(jī)'.center(30,'+'))
host_info_list = [] # 存儲(chǔ)文件中主機(jī)信息
file = 'host/'+choice+'.conf'
with open(file) as f:
for line in f:
line =line.split(':')
print('\t',line[0])
host_info_list.append(line)
while True:
cmd = input('>>>: ')
cmd = cmd.split()
for host in host_info_list:
link = SSH_host(host[0], int(host[1]), host[2], host[3], cmd)
if cmd == []:
continue
else:
if hasattr(link, cmd[0]):
print(cmd[0])
當(dāng)前文章:Python學(xué)習(xí)—paramiko模塊實(shí)現(xiàn)簡(jiǎn)單的ssh與sftp
轉(zhuǎn)載源于:http://www.rwnh.cn/article14/pcojge.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營(yíng)銷、電子商務(wù)、云服務(wù)器、微信小程序、動(dòng)態(tài)網(wǎng)站、品牌網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)