在python3中用paramiko远程连接服务器执行shell命令

前言

paramiko是一个用python语言实现的模块。遵循SSH2协议,支持以加密和认证的方式远程连接服务器。由于使用了python这样跨平台,并且大多数服务器都内置的语言,让paramiko成为了python在Linux运维中的最佳工具之一。

安装

pip install paramiko

使用

#!/bin/python

import paramiko

def get_client(hostname, port, username, password):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname, port, username, password)
    return client

def exec_command(client, cmd):
    stdin, stdout, stderr = client.exec_command(cmd)
    out = stdout.read().decode().strip()
    if out != '':
        print(out)
    err = stderr.read().decode().strip()
    if err != '':
        print(err)

ip = 'IP地址'
user = '用户名'
password = '密码'

client = get_client(ip, 22, user, password)
cmd = 'ls -l'
try:
    print("[%s@%s]$ %s" % (user, ip, cmd))
    exec_command(client, cmd)
except Exception as e:
    print('[%s]: %s' %(ip, e))
finally:
    if client is not None:
        client.close()

上面代码是测试通过了的,可以直接复制使用,只要将IP地址、用户名、密码替换成相应的就可成了。代码中所表述的就是通过get_client函数创建一个SSH客户端连接,然后调用exec_command执行“ls -l”命令并输出结果,最终关闭连接。

本博客采用 知识共享署名-禁止演绎 4.0 国际许可协议 进行许可

本文标题:在python3中用paramiko远程连接服务器执行shell命令

本文地址:https://jizhong.plus/post/2018/01/python-paramiko.html