Python3 进阶---远程操控Linux(centos7.6)

1.安装和配置ssh

(1)ssh服务在centos7上是默认安装了的,可以通过rpm -qa | grep openssh 查看,如下说明是已经安装的了

         如果没有安装,通过指令:yum install openssh  安装

        

(2)配置ssh,编辑文件/etc/ssh/sshd_config

         端口:默认22,可以自行修改

         

        允许使用root用户登录

        

        允许用户账号密码登录

        

(3)启动ssh服务

         systemctl enable sshd

         systemctl start sshd

         

(4)system status sshd:如下,启动服务成功

        

        

2.python端代码

(1)安装第三方库paramiko

         pip install paramiko --default-timeout=60  -i http://pypi.douban.com/simple/  --trusted-host pypi.douban.com

(2)远程执行命令

# -*- coding:utf-8 -*-

import paramiko

# 创建ssh对象
ssh = paramiko.SSHClient()

# 指定连接方式
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接远程Linux主机:远程主机的ip,ssh,用户名,密码
ssh.connect("192.168.xx.xx", 22, "root", "1")

# 执行命令
# stdin = chan.makefile_stdin("wb", bufsize)
# stdout = chan.makefile("r", bufsize)
# stderr = chan.makefile_stderr("r", bufsize)
# exec_command 打开一个新的终端,如果需要执行多条指令,指令之间用;隔开
stdin, stdout, stderr = ssh.exec_command("pwd;cd /usr/local/;mkdir test")
print(stdin)
print(stdout.read().decode("utf-8"))
print(stderr)

# 关闭ssh连接
ssh.close()

(3) 远程Linux文件上传和下载

# -*- coding:utf-8 -*-
import paramiko

# 创建ssh对象
ssh = paramiko.SSHClient()

# 指定连接方式
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接远程Linux主机:远程主机的ip,ssh,用户名,密码
ssh.connect("192.168.xx.xx", 22, "root", "1")

# 创建sftp客户端会话
sftp = ssh.open_sftp()

# 文件上传到远程Linux机器
# 参数1:本地文件路径(包含文件名称),参数2:远程Linux文件路径(包含文件名称)
sftp.put(r"客户端.py", r"/usr/local/test/客户端.py")

# 远程Linux机器文件下载到本地
# 参数1:远程Linux文件路径(包含文件名称),参数2:本地文件路径(包含文件名称)
sftp.get(r"/usr/local/test/a.txt", r"a.txt")

ssh.close()

猜你喜欢

转载自blog.csdn.net/qq_19982677/article/details/108228260