about
bash
pip install paramiko
pip install paramiko==3.3.1
快速上手
读文件
bash
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.11.130', 22, username='root', password='123', timeout=4)
stdin, stdout, stderr = client.exec_command('cat /opt/redis6379/conf/redis6379.conf')
print(stdout.read().decode('utf8'))
"""
daemonize yes
bind 127.0.0.1 192.168.10.147
port 6379
pidfile "/opt/redis6379/pid/redis6379.pid"
logfile "/opt/redis6379/logs/redis6379.log"
dir "/data/redis6379"
save 900 1
save 300 10
save 60 10000
dbfilename "redis.rdb"
appendonly yes
appendfilename "redis.aof"
appendfsync everysec
# Generated by CONFIG REWRITE
supervised systemd
"""
ftp文件上传下载
python
# -*- coding = utf-8 -*-
import os
import paramiko
BASE_DIRS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class SSH(object):
host = 'www.neeo.cc'
port = 22
username = '账号'
password = '密码'
def __init__(self):
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.host, self.port, self.username, self.password, timeout=5)
trans = paramiko.Transport((self.host, self.port))
trans.connect(username=self.username, password=self.password)
self.sftp = paramiko.SFTPClient.from_transport(trans)
def bytes_to_convert(self, size):
'''
递归实现,字节单位转换
精确为最大单位值 + 小数点后2位
示例: bytes_to_convert(1024) # 1.000KB
'''
def strofsize(integer, remainder, level):
if integer >= 1024:
remainder = integer % 1024
integer //= 1024
level += 1
return strofsize(integer, remainder, level)
else:
return integer, remainder, level
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
integer, remainder, level = strofsize(size, 0, 0)
if level + 1 > len(units):
level = -1
return ('{}.{:>02d}{}'.format(integer, remainder, units[level]))
def bar(self, size, total):
""" 进度条 """
convert_total = self.bytes_to_convert(total)
convert_size = self.bytes_to_convert(size)
percentum = "{:.2f}%".format(size / total * 100)
if size == total:
print(f'\r\033[31;1m[{convert_total}/{convert_size}/{percentum}], in transmitting...\033[0m', end='\n')
else:
print(f'\r\033[31;1m[{convert_total}/{convert_size}/{percentum}], in transmitting...\033[0m', end='')
def put(self):
print('开始上传zip压缩包...')
local_path = os.path.join(BASE_DIRS, 'dist.zip')
remote_path = '/data/blogs/dist.zip'
self.sftp.put(local_path, remote_path, callback=self.bar)
print('上传完成...')
def download(self):
print('开始下载zip压缩包...')
local_path = './dist.zip'
remote_path = '/data/blogs/dist.zip'
self.sftp.get(remote_path, local_path, callback=self.bar)
print('下载完成...')
if __name__ == '__main__':
ssh = SSH()
# ssh.put()
ssh.download()
"""
[216.217MB/16.512MB/7.63%], in transmitting...
"""
远程执行命令
python
import paramiko
class SSH(object):
host = 'www.neeo.cc'
port = 22
username = 'root'
password = 'xxxx'
def __init__(self):
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.host, self.port, self.username, self.password, timeout=5)
def exec_command(self):
# 解压远程服务器上的压缩包
# self.ssh.exec_command('cd /data/blogs/ && touch w.py && echo "a" > w.py')
stdin, stdout, stderr = self.ssh.exec_command('ps -ef|grep 8000')
print(stdout.read().decode())
def __del__(self):
self.ssh.close()
if __name__ == '__main__':
obj = SSH()
obj.exec_command()
参考:https://www.cnblogs.com/wangshuo1/p/6265360.html
常见报错
Socket exception: 远程主机强迫关闭了一个现有的连接。 (10054)
win11 + python3.11
paramiko在上传大文件时,会耗时很久,导致报错:
bash
Socket exception: 远程主机强迫关闭了一个现有的连接。 (10054)
原因可能就是建立连接时,超时时间参数没有设置或者设置的时间短了,改长点就好了.
python
import paramiko
class SSH(object):
host = 'www.neeo.cc'
port = 22
username = 'xxx'
password = 'xxxx'
def __init__(self):
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.host, self.port, self.username, self.password, timeout=300) # 就这个timeout参数
trans = paramiko.Transport((self.host, self.port))
trans.connect(username=self.username, password=self.password)
self.sftp = paramiko.SFTPClient.from_transport(trans)