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()
运行效果如下:
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()
以上就是python Paramiko使用示例的详细内容,更多关于python Paramiko的资料请关注其它相关文章!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 群星《2024好听新歌14》十倍音质 U盘音乐 [WAV分轨][966M]
- s14全球总决赛T1战队队员都有谁 LOLs14全球总决赛T1战队介绍
- 英雄联盟faker身价有10亿吗 英雄联盟faker身价介绍一览
- faker大魔王称号怎么来的 faker大魔王称号来源介绍
- PS5 Pro上的蒂法更美了!博主盛赞新机1000%值得购买
- 腾讯互娱再离职一员大将!或因供应商贪腐
- Ayaneo3游戏掌机预热:旗舰定位、造型圆润自带底键
- 动力火车.1999-背叛情歌【上华】【WAV+CUE】
- 刘力扬.2019-Neon.Lit虹【摩登天空】【FLAC分轨】
- 群星.2002-恋爱物语情歌对唱精选2CD(引进版)【滚石】【WAV+CUE】
- 群星《闽南情24K德国HD金碟》2CD[WAV+CUE]
- 周传雄《恋人创世纪》环球唱片[WAV+CUE]
- 关淑怡-《真假情话K2HD》(日本压制)【WAV+CUE】
- 王菲 -《Faye Wong》雨果LPCD45 [WAV+分轨][1G]
- 陈百强《世纪10星·永恒篇》环球[WAV+CUE][1G]