Python3 Advanced ---リモートコントロールLinux(centos7.6)

1.sshをインストールして構成します

(1)sshサービスはデフォルトでcentos7にインストールされます。rpm-qa| grep opensshで確認できます。次の手順は、すでにインストールされています。

         インストールされていない場合は、次のコマンドでインストールします。yuminstall openssh

        

(2)sshを構成し、ファイル/ etc / ssh / sshd_configを編集します

         ポート:デフォルトでは22、自分で変更できます

         

        rootユーザーとしてのログインを許可する

        

        ユーザーアカウントのパスワードログインを許可する

        

(3)sshサービスを開始します

         systemctl enable sshd

         systemctl start sshd

         

(4)システムステータス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