python Paramiko使用示例

作者:Starryland 时间:2022-08-10 08:23:28 

Paramiko 是由 Python 语言编写的一个扩展模块,提供了基于 SSHv2 协议 (包括客户端和服务端)的多种功能实现。通常被用来远程控制类 UNIX 系统。

Paramiko 可以直接使用 pip 命令安装:


$ pip install paramiko

此处不作过多介绍,参考后文中的代码示例。

远程执行 Linux 命令

代码如下:


import paramiko

# 初始化 SSH 客户端,通过用户名密码连接至远程服务器
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname='remoteserver_ip', username='username', password='password')

# 通过 RSA 秘钥验证的方式连接至远程 SSH 服务
# private_key = paramiko.RSAKey.from_private_key_file('~/.ssh/id_rsa')
# client.connect(hostname="remoteserver_ip", username="username", pkey=private_key)

# 远程执行 df -h 命令并打印输出
stdin, stdout, stderr = client.exec_command('df -h')
print(stdout.read().decode('utf-8'))

client.close()

运行效果如下:

python Paramiko使用示例

SFTP 文件传输

示例代码如下:


import paramiko

transport = paramiko.Transport(('hostname_or_ip', port))

# 通过用户名密码完成验证建立连接
transport.connect(username='username', password='password')

# 通过 RSA 私钥文件完成验证建立连接
# private_key = paramiko.RSAKey.from_private_key_file('/path/to/private_key_file')
# transport.connect(username='username', pkey=private_key)

sftp = paramiko.SFTPClient.from_transport(transport)

localpath = "localfile"
remotepath = "remotefile_fullpath"
sftp.put(localpath, remotepath)
print("Successfully uploaded")

transport.close()

综合示例

代码如下(文件名 ssh_connection.py ):


import paramiko
import getpass
import os

class SSHConnection():

def __init__(self, user, host, port=22, password=''):
   self.username = user
   self.host = host
   self.port = port
   self.password = password
   self.keyfile = self.get_keyfile()

def get_keyfile(self, path=os.getcwd()):
   default_keyfile = os.path.join(
     os.environ['HOME'], '.ssh', 'id_rsa')

if 'id_rsa' in os.listdir(path):
     keyfile = os.path.join(path, 'id_rsa')
   elif os.path.isfile(default_keyfile):
     keyfile = default_keyfile
   else:
     keyfile = ''

return keyfile

def connect(self):
   transport = paramiko.Transport((self.host, self.port))

if self.password:
     transport.connect(username=self.username, password=self.password)
   elif self.keyfile:
     transport.connect(
       username=self.username,
       pkey=paramiko.RSAKey.from_private_key_file(self.keyfile))
   else:
     password = getpass.getpass(
       "Password for %s@%s: " % (self.username, self.host))
     transport.connect(username=self.username, password=password)

self._transport = transport

print("Connected to %s as %s" % (self.host, self.username))

def close(self):
   self._transport.close()

def run_cmd(self, command):
   ssh = paramiko.SSHClient()
   ssh._transport = self._transport

stdin, stdout, stderr = ssh.exec_command(command)
   res = stdout.read().decode('utf-8')
   error = stderr.read().decode('utf-8')

if error.strip():
     return error
   else:
     return res

def trans_file(self, localpath, remotepath, method=''):
   sftp = paramiko.SFTPClient.from_transport(self._transport)
   if method == 'put':
     sftp.put(localpath, remotepath)
     print("File %s has uploaded to %s" % (localpath, remotepath))
   elif method == 'get':
     sftp.get(remotepath, localpath)
     print("File %s has saved as %s" % (remotepath, localpath))
   else:
     print('usage: trans_file(localpath, remotepath, method="get/put"')

def __del__(self):
   self.close()

测试结果如下:

(python3) D:\Program\python\devops>python
Python 3.7.2 (default, Jan 2 2019, 17:07:39) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ssh_connection import SSHConnection
>>> client = SSHConnection('starky','127.0.0.1')
>>> client.connect()
Connected to 127.0.0.1 as starky
>>> client.run_cmd('uname -a')
'Linux server1 5.0.0-20-generic #21-Ubuntu SMP Mon Jun 24 09:32:09 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux\n'
>>> client.trans_file('id_rsa.pub', '/home/starky/id_rsa.pub', method='put')
File id_rsa.pub has uploaded to /home/starky/id_rsa.pub
>>> client.run_cmd('ls -l /home/starky/id_rsa.pub')
'-rw-rw-r-- 1 starky starky 410 7月 20 15:01 /home/starky/id_rsa.pub\n'
>>> exit()

来源:https://rollingstarky.github.io/2019/07/20/paramiko-examples/?utm_source=tuicool&utm_medium=referral

标签:python,Paramiko
0
投稿

猜你喜欢

  • MAC系统中添加MYSQL开机启动的方法

    2024-01-13 01:52:53
  • C#如何连接MySQL数据库

    2024-01-27 12:41:16
  • python实现的二叉树算法和kmp算法实例

    2023-08-07 20:50:49
  • django中使用memcached示例详解

    2023-02-10 07:30:50
  • laravel实现简单用户权限的示例代码

    2023-11-14 11:58:29
  • 详解tensorflow载入数据的三种方式

    2023-07-22 19:35:56
  • 使用 OpenCV-Python 识别答题卡判卷功能

    2023-02-03 07:01:43
  • Vue如何实现多页面配置以及打包方式

    2024-05-02 17:09:11
  • response.getWriter().write()向前台打印信息乱码问题解决

    2023-07-05 05:29:37
  • python+pyqt实现右下角弹出框

    2023-09-07 16:04:22
  • Python SMTP发送电子邮件的示例

    2023-09-26 17:57:24
  • 小程序点餐界面添加购物车左右摆动动画

    2024-04-27 15:22:36
  • Python基于scrapy采集数据时使用代理服务器的方法

    2022-06-03 08:37:04
  • PyTorch中topk函数的用法详解

    2022-11-08 13:55:52
  • Python实现灰色关联分析与结果可视化的详细代码

    2023-08-03 15:01:56
  • Pytorch模型迁移和迁移学习,导入部分模型参数的操作

    2021-08-05 09:18:16
  • 微信小程序动态添加分享数据

    2024-06-20 16:23:00
  • Pycharm添加虚拟解释器报错问题解决方案

    2022-05-28 04:07:53
  • 对python使用telnet实现弱密码登录的方法详解

    2023-12-28 02:52:46
  • thinkphp实现多语言功能(语言包)

    2024-05-22 10:05:21
  • asp之家 网络编程 m.aspxhome.com