展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

SSH远程操作

  • 安装库
pip install paramiko
  • 案例1
import paramiko
# 创建SSHClient 实例对象
ssh = paramiko.SSHClient()
# 设置信任远程机器,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh连接远程机器,参数为 地址、端口、用户名、密码
ssh.connect("192.168.0.102", 22, "root", "root")
# 执行命令,创建目录 logs
ssh.exec_command("mkdir logs")
# 关闭ssh连接
ssh.close()
  • 执行结果
[root@VM-12-15-centos ~]# pwd
/root
[root@VM-12-15-centos ~]# ls
logs
  • 案例2:获取屏幕输出
import paramiko
# 创建SSHClient 实例对象
ssh = paramiko.SSHClient()
# 设置信任远程机器,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh连接远程机器,参数为 地址、端口、用户名、密码
ssh.connect("192.168.0.102", 22, "root", "root")
cmd = 'docker ps'
# 每次执行命令会返回3个对象,对应标准输入、标准输出、标准错误
stdin, stdout, stderr = ssh.exec_command(cmd)
# 从 标准输出、标准错误 中读取字节
outputBytes = stdout.read()+ stderr.read()
# 解码为字符串
outputStr = outputBytes.decode('utf8')
print(outputStr)
# 关闭ssh连接
ssh.close()
  • 执行结果
C:\Python310\python.exe C:/work/git/default-case-repo/02/test01/ssh操作/test2.py
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3b546c5a42b9 redis:latest "docker-entrypoint.s…" 7 weeks ago Up 7 weeks 0.0.0.0:6379->6379/tcp adoring_ganguly
bfabb860bd90 mysql "docker-entrypoint.s…" 8 weeks ago Up 8 weeks 0.0.0.0:3306->3306/tcp, 33060/tcp mysql
Process finished with exit code 0
  • 命令的前后关联
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.2.100", 22, "byhy", "byhy5200")
# 创建目录 testdir
ssh.exec_command("mkdir testdir")
# 进入目录 testdir
ssh.exec_command("cd testdir")
# 查看当前路径
stdin, stdout, stderr = ssh.exec_command("pwd")
print(stdout.read())
ssh.close()
  • 以上代码中cd testdir和pwd不在同一个channel,想要在同一个channel中,写法如下
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.2.100", 22, "byhy", "byhy5200")
# 创建目录 testdir
ssh.exec_command("mkdir testdir")
# 用一行命令 进入目录 testdir 并且 查看当前路径
stdin, stdout, stderr = ssh.exec_command("cd testdir;pwd")
print(stdout.read())
ssh.close()
  • 文件传输
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.2.100", 22, "byhy", "byhy5200")
# 打开一个sftp连接,返回sftp连接对象
sftp = ssh.open_sftp()
# put方法上传文件,第1个参数是本地路径,第2个参数是远程路径
sftp.put('install.zip', '/home/byhy/install.zip')
# get方法下载文件,第1个参数是远程路径,第2个参数是本地路径
sftp.get('/home/byhy/log.zip', 'd:/log.zip')
# 关闭sftp连接
sftp.close()
# 关闭ssh连接
ssh.close()
posted @   DogLeftover  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
历史上的今天:
2022-10-08 标识符、运算符
2022-10-08 字面量、注释、变量、数据类型、数据类型转换
2022-10-08 下载安装go,eclipse配置go
2022-10-08 python开发环境
点击右上角即可分享
微信分享提示