paramiko模块

paramiko模块远程密码连接

paramiko是基于ssh用于连接远程服务器做操作:远程执行命令, 上传文件, 下载文件

import paramiko
#ssh root@172.25.254.250

创建一个ssh对象;

client = paramiko.SSHClient()

2. 解决问题:如果之前没有;连接过的ip, 会出现

#Are you sure you want to continue connecting (yes/no)? yes

自动选择yes

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

3. 连接服务器

client.connect(
hostname=‘172.25.254.1’,
username=‘root’,
password=‘westos’
)

4. 执行操作

stdin, stdout, stderr = client.exec_command(‘hostname’)

5. 获取命令的执行结果;

print(stdout.read().decode(‘utf-8’))

6. 关闭连接

client.close()

批量远程密码连接

from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
def connect(cmd, hostname, user, password):

import paramiko
#ssh root@172.25.254.250

创建一个ssh对象;

client = paramiko.SSHClient()

2. 解决问题:如果之前没有;连接过的ip, 会出现

####### Are you sure you want to continue connecting (yes/no)? yes
####### 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:

3. 连接服务器

client.connect(
hostname=hostname,
username=user,
password=password
)

except NoValidConnectionsError as e:

return “主机%s连接失败” %(hostname)

except AuthenticationException as e:

return “主机%s密码错误” % (hostname)

except Exception as e:

return "未知错误: ", e

else:

4. 执行操作

stdin, stdout, stderr = client.exec_command(‘hostname’)

5. 获取命令的执行结果;

res = stdout.read().decode(‘utf-8’)

6. 关闭连接

client.close()

return res

if name == ‘main’:

with open(‘doc/hosts.txt’) as f:

for line in f:

#172.25.254.1:root:westos
hostname, username, password = line.split("?
res = connect(‘hostname’, hostname, username, password )
print(hostname.center(50, ‘*’))
print(“主机名:”, res)

其中host中的内容需要我们以172.25.254.1:root:westos的格式写入

paramiko基于公钥和私钥连接

import paramiko
#ssh root@172.25.254.250

创建一个ssh对象;

client = paramiko.SSHClient()

实例化一个私钥对象

private_key = paramiko.RSAKey.from_private_key_file(‘doc/id_rsa’)

2. 解决问题:如果之前没有;连接过的ip, 会出现

#Are you sure you want to continue connecting (yes/no)? yes

自动选择yes

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

3. 连接服务器

client.connect(
hostname=‘172.25.254.3’,
username=‘root’,
pkey= private_key ,
)

4. 执行操作

stdin, stdout, stderr = client.exec_command(‘hostname’)

5. 获取命令的执行结果;

print(stdout.read().decode(‘utf-8’))

6. 关闭连接

client.close()

基于paramiko的远程连接上传和下载

import paramiko

验证用户名和密码是否正确

from paramiko import SSHException,AuthenticationException
try:

transport=paramiko.Transport((‘172.25.254.28’,22))
transport.connect(username=‘root’,password=‘redhat’)

根据创建并验证成功的通道,创建sftp客户端

sftp=paramiko.SFTPClient.from_transport(transport)

except SSHException as e:

print(‘主机不存在’)

except AuthenticationException as e :

print(‘密码错误’)

except Exception as e:

print(‘连接出错’)

else:

sftp.put(’/etc/passwd’,’/mnt/病毒’) # 上床
sftp.get(’/mnt/病毒’,’/tmp/GG’) #下载

finally:

transport.close()

paramiko的再次封装

import logging
import paramiko
import os
from paramiko import SSHException
from paramiko.ssh_exception import
NoValidConnectionsError,AuthenticationException

将debug等级以下的结果写入日志中

logging.basicConfig(filename=‘my.log’, level=logging.DEBUG, format="%>(asctime)s-%(filename)s-%(lineno)d- %(levelname)s: %(message)s ")
class SshRemoteHost(object):

def init(self,host,user,pwd,cmd,port=22):

self.host=host
self.user=user
self.pwd=pwd
self.cmd=cmd
self.port=port

def run(self):

cmd_str =self.cmd.split()[0]
if hasattr(self,‘do_’+ cmd_str): # 判断是否有do_cmd方法

getattr(self,‘do_’ + cmd_str)()

else:

logging.error(‘目前不支持该操作…目前仅支持cmd,put,get’)
print(‘目前不支持该操作…目前仅支持cmd,put,get’)

def do_cmd(self):

print(‘正在执行命令…’)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:

client.connect(
hostname=self.host,
username=self.user,
password=self.pwd
)

except NoValidConnectionsError as e:

logging.error(‘主机%s连接失败’ % (self.host))
print(‘主机%s连接失败’ % (self.host))

except AuthenticationException as e:

print(‘主机%s密码错误’ % (self.host))

except Exception as e:

print(‘未知错误:%s’ % e)

else:

cmd=’’.join(self.cmd.split()[1:])
stdin, stdout, stderr = client.exec_command(cmd)
res = stdout.read().decode(‘utf-8’)
client.close()
print(res)

def do_put(self):

print(‘正在批量上传文件…’)
try:

transport = paramiko.Transport((self.host, int(self.port)))
transport.connect(username=self.user, password=self.pwd)
sftp = paramiko.SFTPClient.from_transport(transport)

except AuthenticationException as e:

print(‘密码错误’)

except SSHException as e:

print(‘主机不存在’)

except Exception as e:

print(‘连接出错’)

except FileNotFoundError as e:

print(‘文件不存在’)

else:

filenames=self.cmd.split()[1:]
if len(filenames) == 2:

sftp.put(filenames[0], filenames[1])

else:

print(‘命令错误,用法:put 源文件,目标文件夹’)

#sftp.put(’/etc/passwd’, ‘/mnt/病毒’)
#sftp.get(’/mnt/病毒’, ‘/tmp/GG’)
transport.close()

def do_get(self):

print(‘正在批量下载文件…’)
try:

transport = paramiko.Transport((self.host, int(self.port)))
transport.connect(username=self.user, password=self.pwd)
sftp = paramiko.SFTPClient.from_transport(transport)

except AuthenticationException as e:

print(‘密码错误’)

except SSHException as e:

print(‘主机不存在’)

except Exception as e:

print(‘连接出错’)

except FileNotFoundError as e:

print(‘文件不存在’)

else:

filenames=self.cmd.split()[1:]
if len(filenames) == 2:

sftp.get(filenames[0], filenames[1] + ‘_’ + self.host)

else:

print(‘命令错误,用法:get 源文件,目标文件夹’)

#sftp.put(’/etc/passwd’, ‘/mnt/病毒’)
#sftp.get(’/mnt/病毒’, ‘/tmp/GG’)
transport.close()

def main():

CONFDIR=‘conf’

1.主机组显示

print(‘主机组显示’.center(50,’*’))
groups= [file.rstrip(’.conf’) for file in os.listdir(CONFDIR) if file.endswith(’.conf’)]
for group in groups:

print(’\t’,group)

while True:

choiceGroup=input(‘请输入需要操作的主机:’)
if choiceGroup not in groups:

print(’%s不存在请重新输入’ %(choiceGroup))

else:

2.根据主机,显示包含的ip/主机名

infor=’%s主机组包含的主机’ %(choiceGroup)
print(infor.center(50,’*’))
hostinfors=[ ] # 存储需要操作的主机信息
with open(’%s/%s.conf’ %(CONFDIR,choiceGroup)) as f1:

for line in f1:

#print(line.split(’:’)[0])
hostinfors.append(line.strip().split(’:’))
hostname,port,user,passwd=line.strip().split(’:’)
print(hostname)

print(‘批量执行脚本’.center(50,’*’))
while True:

cmd=input(’>>:’)
if cmd:

if cmd in [‘exit’,‘quit’]:

print(‘执行结束,退出中…’)
exit(0)

else:

for host in hostinfors:

hostname,port,user,passwd=host
print(hostname.center(50,’*’))
sshObj= SshRemoteHost(hostname,user,passwd,cmd,port)
sshObj.run()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值