python使用paramiko执行服务器脚本并拿到实时结果
作者:LanLanDeMing 时间:2021-06-02 17:54:29
paramiko 执行服务器脚本并拿到实时结果
import paramiko
cmd = '{0}/{1} linux 32'.format('/root/installer', 'make_client_installer.sh')
print(cmd)
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('xx.xx.xx.xx', port, 'username', 'password', timeout=5)
stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
while not stdout.channel.exit_status_ready():
result = stdout.readline()
print(result)
if stdout.channel.exit_status_ready():
a = stdout.readlines()
print(a)
break
ssh.close()
except Exception as e:
print(e)```
python 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',
port=22,
username='root',
password='redhat')
# 4. 执行操作
stdin, stdout, stderr = client.exec_command('hostnaewdeme')
# 5. 获取命令的执行结果;
result = stdout.read().decode('utf-8')
print(result)
print(stderr.read())
# 6. 关闭连接
client.close()
paramiko批量远程密码连接
# 基于ssh用于连接远程服务器做操作:远程执行命令, 上传文件, 下载文件
import paramiko
import logging
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def connect(cmd, hostname, port=22, username='root', password='westos'):
# 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,
port=port,
username=username,
password=password)
print("正在连接主机%s......." %(hostname))
except NoValidConnectionsError as e:
print("连接失败")
except AuthenticationException as e:
print("密码错误")
else:
# 4. 执行操作
stdin, stdout, stderr = client.exec_command(cmd)
# 5. 获取命令的执行结果;
result = stdout.read().decode('utf-8')
print(result)
# 6. 关闭连接
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', hostname, port, username, password)
paramiko基于公钥密钥连接
# 基于ssh用于连接远程服务器做操作:远程执行命令, 上传文件, 下载文件
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
def connect(cmd, hostname, port=22, user='root'):
# ssh root@172.25.254.250
# 创建一个ssh对象;
client = paramiko.SSHClient()
# 返回一个私钥对象
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
# 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,
port=port,
username=user,
pkey=private_key
)
# 4. 执行操作
stdin, stdout, stderr = client.exec_command(cmd)
except NoValidConnectionsError as e:
print("连接失败")
except AuthenticationException as e:
print("密码错误")
else:
# 5. 获取命令的执行结果;
result = stdout.read().decode('utf-8')
print(result)
finally:
# 6. 关闭连接
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.39', 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()
基于密钥上传下载
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再次封装
import os
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException
class SshRemoteHost(object):
def __init__(self, hostname, port, user, passwd, cmd):
# 指的不是shell命令
# cmd shell命令
# put
# get
self.hostname = hostname
self.port = port
self.user = user
self.passwd = passwd
self.cmd = cmd
def run(self):
"""默认调用的内容"""
# cmd hostname
# put
# get
cmd_str = self.cmd.split()[0] # cmd
# 类的反射, 判断类里面是否可以支持该操作?
if hasattr(self, 'do_'+ cmd_str): # do_cmd
getattr(self, 'do_'+cmd_str)()
else:
print("目前不支持该功能")
def do_cmd(self):
# 创建一个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=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:
# 4. 执行操作
# cmd uname
# cmd ls /etc/
# *******注意:
cmd = ' '.join(self.cmd.split()[1:])
stdin, stdout, stderr = client.exec_command(cmd)
# 5. 获取命令的执行结果;
result = stdout.read().decode('utf-8')
print(result)
# 6. 关闭连接
client.close()
def do_put(self):
# put /tmp/passwd /tmp/passwd
# put /tmp/passwd /tmp/pwd
# put /tmp/passwd # 将本机的/tmp/passwd文件上传到远程主机的/tmp/passwd;
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("正在下载.....")
# 2. 根据选择的主机组, 显示包含的主机IP/主机名;
# 3. 让用户确认信息, 选择需要批量执行的命令;
# - cmd shell命令
# - put 本地文件 远程文件
# - get 远程文件 本地文件
def main():
# 1. 选择操作的主机组:eg: mysql, web, ftp
groups = [file.rstrip('.conf') for file in os.listdir('conf')]
print("主机组显示:".center(50, '*'))
for group in groups: print('\t', group)
choiceGroup = input("清选择批量操作的主机组(eg:web):")
# 2. 根据选择的主机组, 显示包含的主机IP/主机名;
# 1). 打开文件conf/choiceGroup.conf
# 2). 依次读取文件每一行,
# 3). 只拿出ip
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()]
# 3. 让用户确认信息, 选择需要批量执行的命令;
print("批量执行脚本".center(50, '*'))
while True:
cmd = input(">>:").strip() # cmd uname
if cmd:
if cmd == 'exit' or cmd =='quit':
print("执行结束, 退出中......")
break
# 依次让该主机组的所有主机执行
for info in hostinfos:
# 'ip:port:user:passwd'
host, port, user, passwd = info.split(":")
print(host.center(50, '-'))
clientObj = SshRemoteHost(host, port, user, passwd, cmd)
clientObj.run()
if __name__ == '__main__':
main()
来源:https://blog.csdn.net/LanlanDeming/article/details/113700202
标签:python,paramiko,服务器,脚本,实时结果
0
投稿
猜你喜欢
写一个简单的bat脚本执行php文件
2024-03-07 09:18:12
sqlserver 多库查询 sp_addlinkedserver使用方法(添加链接服务器)
2011-09-30 11:49:22
Web Jmeter–接口测试工具详解
2022-06-27 04:24:32
ASP数据库编程SQL常用技巧
2024-01-20 04:53:59
SQL字符串处理函数大全
2024-01-25 07:09:13
未能加载文件或程序集“XXX”或它的某一个依赖项。试图加载格式不正确的程序。
2023-07-01 00:38:21
SQL分页查询存储过程代码分享
2024-01-12 23:51:04
aws 通过boto3 python脚本打pach的实现方法
2021-09-14 23:33:19
python矩阵的基本运算及各种操作
2023-01-12 11:37:27
python装饰器相当于函数的调用方式
2021-05-13 13:39:03
vue中Axios添加拦截器刷新token的实现方法
2024-05-13 09:07:41
基于python if 判断选择结构的实例详解
2023-01-15 22:45:03
Flask框架模板继承实现方法分析
2021-02-20 04:09:52
Python3.10耙梳加密算法Encryption种类及开发场景
2021-07-19 00:46:55
Python爬虫实现抓取电影网站信息并入库
2023-12-25 02:42:32
python super()函数的详解
2023-08-08 10:09:42
使用html+js+css 实现页面轮播图效果(实例讲解)
2024-02-24 01:48:44
详细解读Python中的__init__()方法
2023-03-25 17:10:27
flask使用session保存登录状态及拦截未登录请求代码
2021-02-22 12:00:57
提高MYSQL查询效率的三个有效的尝试
2009-02-27 16:08:00