[python] paramiko remote operation Linux

Background Note:

During the development server or operation and maintenance process, we need to log in to Linux to download data, upload data, execute scripts and other operations. If you are used to the windows system and do not want to use Xshell or Mobax or Linux operating system to operate, then python provides a very convenient third-party library for you to log in to Linux remotely under windows. Here is a summary of several methods for operating linux with non-public key keys:

Pay attention to "Test Development Automation" Gong Zhonghao, get the source code)


1. Remote login

import paramiko

ssh = paramiko.SSHClient()                                     # 创建SSH对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())      # 允许连接不在know_hosts文件中的主机。即:解决问题:如果之前没有,连接过的ip,会出现选择yes
# 连接服务器(根据自己的情况选择)
ssh.connect(hostname='192.168.xxx.xxx', username='xxx', password='xxx')     # 用户名和密码登录
stdin, stdout, stderr = ssh.exec_command('ls -lh')
result = stdout.read().decode('utf-8')   # 获取命令结果
print(result)                            # 输出返回的结果
ssh.close()                              # 关闭连接

2. File upload and download

Method 1: Pay attention to "Test Development Automation" Gong Zhonghao, get the source code)

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.xxx.xxx', username='xxxx', password='xxxx')

sftp = ssh.open_sftp()
sftp.put(r'D:\xxxx\xxxx.sh', '/home/xxxx/xxxx.sh')       # 将windows文件上传至Linux
sftp.get('/home/xxxx/xxxx.sh', r'D:\xxxx\xxxx.sh')       # 将Linux文件下载至windows

sftp.close()

stdin, stdout, stderr = ssh.exec_command('sh /home/xxxx/xxxx.sh')    # 运行sh文件
result = stdout.read().decode('utf-8')
print(result)
ssh.close()

Method 2: Pay attention to "Test Development Automation" Gong Zhonghao, get the source code)

import paramiko

#获取Transport实例
tran = paramiko.Transport("192.168.xxx.xxx", 22)
#连接SSH服务端
tran.connect(username="xxx", password="xxx")
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)
#设置上传的本地/远程文件路径
localpath= r"D:\xxxx\xxxx.py"    #本地文件路径
remotepath= r"/home/xxxx/xxxx.py"  #上传对象保存的文件路径
#执行上传动作
sftp.put(localpath, remotepath)
# 执行下载动作
sftp.get(remotepath, localpathwen)
tran.close()

3. sudo permissions:

Pay attention to "Test Development Automation" Gong Zhonghao, get the source code)

import paramiko

hostname = "192.168.xxx.xxx"
username = 'ubuntu'
password = 'ubuntu'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password)

stdin, stdout, stderr = ssh.exec_command('sudo reboot', get_pty=True)  # sudo权限
stdin.write('ubuntu'+'\n')   # 输入密码

result = stdout.read().decode('utf-8')
print(result)
ssh.close()

4. Bulk Links

Pay attention to "Test Development Automation" Gong Zhonghao, get the source code)

import paramiko
from paramiko.ssh_exception import NoValidConnectionsError
from paramiko.ssh_exception import AuthenticationException


def connect(cmd, hostname,port=22,username='root',passwd='westos'):
    ##1.创建一个ssh对象
    client = paramiko.SSHClient()
    #2.解决问题:如果之前没有,连接过的ip,会出现选择yes或者no的操作,
    ##自动选择yes
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    #3.连接服务器
    try:
        client.connect(hostname=hostname, port=port, username=username, password=passwd)
        print('正在连接主机%s......'%(hostname))

    except NoValidConnectionsError as e: ###用户不存在时的报错
        print("连接失败")
    except AuthenticationException as t: ##密码错误的报错
        print('密码错误')
    else:
        #4.执行操作
        stdin,stdout, stderr = client.exec_command(cmd)
        #5.获取命令执行的结果
        result=stdout.read().decode('utf-8')
        print(result)
        #6.关闭连接
    finally:
        client.close()

# 为提高效率,此处建议使用多线程
connect('ls -h', hostname='192.168.xxx.xxx', username='Xxxx', passwd='xxx')
connect('ls -h', hostname='192.168.xxx.xxx', username='xxxx', passwd='xxxx')

If it is helpful to you, please pay attention and go! ! !

Guess you like

Origin blog.csdn.net/weixin_44244190/article/details/129423102