paramiko远程密码连接
基于ssh用于连接远程服务器作操作,可以远程执行命令,上传文件,下载文件等
import parpmiko
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddpolicy())
clinet.connect(hostname='172.25.254.37',
port=22,
username='root',
password='westos')
stdio,stdout,stderr =clinet.exec_command('hostnaewdeme')
result=stdout.read().decode('utf-8')
print(result)
client.close()
paramiko远程密码连接.plus
import parpmiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def connect(cmd,hostname,port=22,username='root,passwd='westos')
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddpolicy())
try:
clinet.connect(hostname='172.25.254.37',
port=22,
username=username,
password=passwd)
print("正在连接主机%s......"%(hostname))
expect NoValidConnectionsError as e:
print("连接失败")
except AuthenticationException as e:
print("密码错误")
else:
stdio,stdout,stderr =clinet.exec_command('hostnaewdeme')
result=stdout.read().decode('utf-8')
print(result)
client.close()
with open('host.txt') as f:
for line in f:
line=line.strip()
hostname,port,username,password=line.split(':')
print(hostname.center(50,"*")
connect('hostname',hostaname,port,username,passwd)
paramiko基于公钥密钥连接:
基于ssh用于连接远程服务器做操作:远程执行命令, 上传文件, 下载文件
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def connect(cmd, hostname, port=22, user='root'):
client = paramiko.SSHClient()
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname,
port=port,
username=user,
pkey=private_key
)
stdin, stdout, stderr = client.exec_command(cmd)
except NoValidConnectionsError as e:
print("连接失败")
except AuthenticationException as e:
print("密码错误")
else:
result = stdout.read().decode('utf-8')
print(result)
finally:
client.close()
for count in range(254):
host = '172.25.254.%s' %(count+1)
print(host.center(50, '*'))
connect('uname', host)
基于用户名密码上传下载:
import paramiko
transport = paramiko.Transport(('172.25.254.37', 22))
transport.connect(username='root', password='westos')
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put('/tmp/kiosk', '/mnt/kiosk1')
sftp.get('/mnt/kiosk', '/home/kiosk/Desktop/day18/kiosk')
transport.close()
基于密钥上传和下载
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
transport = paramiko.Transport(('172.25.254.37', 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再次封装:
import os
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException
class SshRemoteHost(object):
def __init__(self, hostname, port, user, passwd, cmd):
self.hostname = hostname
self.port = port
self.user = user
self.passwd = passwd
self.cmd = cmd
def run(self):
cmd_str = self.cmd.split()[0]
if hasattr(self, 'do_'+ cmd_str):
getattr(self, 'do_'+cmd_str)()
else:
print("目前不支持该功能")
def do_cmd(self):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=self.hostname,
port=self.port,
username=self.user,
password=self.passwd)
print("正在连接主机%s......." % (self.hostname))
except NoValidConnectionsError as e:
print("连接失败")
except AuthenticationException as e:
print("密码错误")
else:
cmd = ' '.join(self.cmd.split()[1:])
stdin, stdout, stderr = client.exec_command(cmd)
result = stdout.read().decode('utf-8')
print(result)
client.close()
def do_put(self):
print("正在上传.....")
try:
transport = paramiko.Transport((self.hostname, int(self.port)))
transport.connect(username=self.user, password=self.passwd)
except SSHException as e:
print("连接失败")
else:
sftp = paramiko.SFTPClient.from_transport(transport)
newCmd = self.cmd.split()[1:]
if len(newCmd) == 2:
sftp.put(newCmd[0], newCmd[1])
print("%s文件上传到%s主机的%s文件成功" %(newCmd[0],
self.hostname, newCmd[1]))
else:
print("上传文件信息错误")
transport.close()
def do_get(self):
print("正在下载.....")
groups = [file.rstrip('.conf') for file in os.listdir('conf')]
print("主机组显示:".center(50, '*'))
for group in groups: print('\t', group)
choiceGroup = input("清选择批量操作的主机组(eg:web):")
print("主机组包含主机:".center(50, '*'))
with open('conf/%s.conf' %(choiceGroup)) as f:
for line in f:
print(line.split(':')[0])
f.seek(0,0)
hostinfos = [line.strip() for line in f.readlines()]
print("批量执行脚本".center(50, '*'))
while True:
cmd = input(">>:").strip()
if cmd:
if cmd == 'exit' or cmd =='quit':
print("执行结束, 退出中......")
break
for info in hostinfos:
host, port, user, passwd = info.split(":")
print(host.center(50, '-'))
clientObj = SshRemoteHost(host, port, user, passwd, cmd)
clientObj.run()