使用Python实现远程命令执行
最编程
2024-02-10 10:05:23
...
# coding: utf-8
import paramiko
import re
from time import sleep
# 定义一个类,表示一台远端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(u'连接%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(u'连接%s失败,进行重试' %self.ip)
self.try_times -= 1
else:
print(u'重试3次失败,结束程序')
exit(1)
# 断开连接
def close(self):
self.chan.close()
self.t.close()
# 发送要执行的命令
def send(self, cmd):
cmd += '\r'
# 通过命令执行提示符来判断命令是否执行完成
p = re.compile(r']$')
result = ''
# 发送要执行的命令
self.chan.send(cmd)
# 回显很长的命令可能执行较久,通过循环分批次取回回显
while True:
sleep(2)
ret = self.chan.recv(65535)
ret = ret.decode('utf-8')
result += ret
if p.search(ret):
print(result)
return(result)
if __name__ == '__main__':
host = Linux('172.16.1.5', 'linyouyi', '123456')
host.connect()
host.send('ll')
host.close()
推荐阅读
-
使用 ganache 实现 Web3js 与区块链交互的步骤及问题解决方案:未找到命令 "express "等。
-
在多种不同的 Common Lisp 实现(CLISP、CCL、SBCL)中执行 shell 命令的功能
-
使用 pip update 命令和清华镜像快速安装 OpenCV-python
-
使用 git 命令和 vscode 从零开始从远程代码库中拉取、提交、合并和推送分支,并在项目中进行练习
-
贪婪算法在 Python、JavaScript、Java、C++ 和 C# 中的多种实现及其在硬币变化、分数骑士、活动选择和使用哈夫曼编码的最小生成树问题中的应用实例
-
ssh 远程命令执行
-
在 Django 中使用 python 的 django-mptt 库来实现无限级树结构非常直观且易于实现
-
杂项]使用 CUDA 实现 tensorflow 的 GPU 加速 - 以恩智浦的 eIQ Portal 命令行环境为例。
-
使用 WPAD/PAC 和 JScript 在 win11 中远程执行代码
-
使用 WPAD/PAC 和 JScript 在 win11 中远程执行代码1