python3模拟实现xshell远程执行linux命令的方法

作者:Liu-YanLin 时间:2022-05-26 11:45:14 

依赖包:pip install paramiko

源码demo:


from time import *
import paramiko
# 定义一个类,表示一台远端linux主机
class Linux(object):
 # 通过IP, 用户名,密码,超时时间初始化一个远程Linux主机
 def __init__(self, ip, username, password, timeout=30):
   self.ip = ip
   self.username = username
   self.password = password
   self.timeout = timeout
   # transport和chanel
   self.t = ''
   self.chan = ''
   # 链接失败的重试次数
   self.try_times = 3

# 调用该方法连接远程主机
 def connect(self):
   while True:
     # 连接过程中可能会抛出异常,比如网络不通、链接超时
     try:
       self.t = paramiko.Transport(sock=(self.ip, 22))
       self.t.connect(username=self.username, password=self.password)
       self.chan = self.t.open_session()
       self.chan.settimeout(self.timeout)
       self.chan.get_pty()
       self.chan.invoke_shell()
       # 如果没有抛出异常说明连接成功,直接返回
       print('连接%s成功' % self.ip)
       # 接收到的网络数据解码为str
       print(self.chan.recv(65535).decode('utf-8'))
       return
     # 这里不对可能的异常如socket.error, socket.timeout细化,直接一网打尽
     except Exception as e1:
       if self.try_times != 0:
         print('连接%s失败,进行重试' % self.ip)
         self.try_times -= 1
       else:
         print('重试3次失败,结束程序')
         exit(1)

# 断开连接
 def close(self):
   self.chan.close()
   self.t.close()

# 发送要执行的命令
 def send(self, cmd):
   cmd += '\r'
   result = ''
   # 发送要执行的命令
   self.chan.send(cmd)
   # 回显很长的命令可能执行较久,通过循环分批次取回回显,执行成功返回true,失败返回false
   while True:
     sleep(0.5)
     ret = self.chan.recv(65535)
     ret = ret.decode('utf-8')
     result += ret
     return result
 '''
 发送文件
 @:param upload_files上传文件路径 例如:/tmp/test.py
 @:param upload_path 上传到目标路径 例如:/tmp/test_new.py
 '''
 def upload_file(self,upload_files,upload_path):
   try:
     tran=paramiko.Transport(sock=(self.ip, self.port))
     tran.connect(username=self.username, password=self.password)
     sftp = paramiko.SFTPClient.from_transport(tran)
     result=sftp.put(upload_files, upload_path)
     return True if result else False
   except Exception as ex:
     print(ex)
     tran.close()
   finally:
     tran.close()

# 连接正常的情况
if __name__ == '__main__':
 host = Linux('192.168.16.57', 'root', '+B*A15*EFpKG') # 传入Ip,用户名,密码
 host.connect()
 # result = host.send('ls') # 发送一个查看ip的命令
 def input_cmd(str):
   return input(str)
 tishi_msg="输入命令:"
 while True:
   msg=input(tishi_msg)
   if msg=="exit":
     host.close()
     break
   else:
     res=host.send(msg)
     data=res.replace(res.split("\n")[-1],"")
     tishi_msg=res.split("\n")[-1]
     print(res.split("\n")[-1] + data.strip("\n"))

运行代码测试效果图:

python3模拟实现xshell远程执行linux命令的方法

来源:https://blog.csdn.net/qq_32502511/article/details/79849826

标签:python3,xshell,linux
0
投稿

猜你喜欢

  • asp如何让页面背景五彩缤纷?

    2010-05-13 16:38:00
  • JDBC获取数据库连接的5种方式实例

    2024-01-19 05:14:05
  • IE和Firefox的js兼容性整理

    2007-11-21 19:40:00
  • python批量解压zip文件的方法

    2022-08-26 16:20:00
  • 使用Keras中的ImageDataGenerator进行批次读图方式

    2023-07-02 03:49:50
  • asp如何统计字符串出现的次数?

    2009-11-25 20:36:00
  • pytorch: Parameter 的数据结构实例

    2022-10-19 22:28:22
  • Python Django2 model 查询介绍(条件、范围、模糊查询)

    2023-11-02 15:32:09
  • TensorFlow2.1.0最新版本安装详细教程

    2021-11-08 00:14:02
  • Python实现利用163邮箱远程关电脑脚本

    2023-08-29 10:08:08
  • 利用Python脚本实现传递参数的三种方式分享

    2023-07-11 03:45:44
  • python中os库的函数使用

    2022-05-03 22:16:57
  • Linux下mysql的root密码修改方法

    2024-01-13 17:39:44
  • sqlserver中在指定数据库的所有表的所有列中搜索给定的值

    2011-09-30 11:27:38
  • MySQL也能并发导入数据

    2010-03-25 10:38:00
  • 网页设计标准尺寸参考

    2007-12-29 20:42:00
  • Python3.6正式版新特性预览

    2023-11-02 09:27:09
  • 简单讲解Python中的字符串与字符串的输入输出

    2021-09-14 18:57:08
  • 分页存储过程(二)在sqlserver中返回更加准确的分页结果

    2024-01-13 03:42:43
  • 关于vuex状态刷新网页时数据被清空问题及解决

    2024-04-30 10:22:18
  • asp之家 网络编程 m.aspxhome.com