Python学习—paramiko模块实
短信预约 -IT技能 免费直播动态提醒
paramiko模块
paramiko模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件的功能。这是一个第三方的软件包,使用之前需要安装。
import paramiko
# ssh root@ip
# 创建一个ssh对象
client = paramiko.SSHClient()
#如果第一次连接陌生的IP,自动选择yes确认连接
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
client.connect(hostname='111.231.215.66',port=22,username='手动屏蔽帐号',password='手动屏蔽密码')
# 执行操作
stdin,stdout,stderr = client.exec_command('hostname')
# 获取命令执行结果
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)
# 关闭连接
client.close()
例子1:
连接文件 主机信息.txt 中的所有主机
不能连接返回连接失败,成功连接,返回其主机名
把连接情况写入文件。
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主机名:%s' %r)
return '连接成功......'+'\n主机名:%s' %r
with open('连接状况.txt','w') as f,open('主机信息.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主机名:%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综合练习实例1
import os
import paramiko
group = [file.rstrip('.conf') for file in os.listdir('host')]
print('主机组'.center(30,'+'))
for i,g in enumerate(group):
print('\t',str(i+1),'\t',g)
choice = input('选择操作组:')
print('主机'.center(30,'+'))
host_info_list = [] # 存储文件中主机信息
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('连接主机 ',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('连接主机 ', 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('暂时没有这个命令的操作......',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封装实例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('连接主机 ',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('连接主机 ', 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('连接主机 ', 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('主机组'.center(30,'+'))
for i,g in enumerate(group):
print('\t',str(i+1),'\t',g)
choice = input('选择操作组:')
print('主机'.center(30,'+'))
host_info_list = [] # 存储文件中主机信息
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])
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341