下载方式:
pip install paramiko
pip install fabric
离线包下载
pip download paramiko -d /path/
pip install /path/paramiko-x.x.x.tar.gz
pip wheel paramiko -w /path
pip install /path/paramiko-x.x.x.whl
安装:pip install /path/paramiko-x.x.x.whl
# python两种连接远程机的方式
from fabric import Connection
import paramiko
def param():
# 远程机器信息
hostname = '10.201.21.24'
port = 22
username = 'admin'
password = 'xxx'
remote_path = '/c/down/test.txt' # 远程文件路径
# 创建一个SSH客户端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接远程机器
ssh.connect(hostname, port, username, password)
# 创建一个SFTP客户端
sftp = ssh.open_sftp()
# 从远程机器读取文件内容
remote_file = sftp.file(remote_path, 'r')
file_contents = remote_file.read()
# 关闭SFTP和SSH连接
remote_file.close()
sftp.close()
ssh.close()
# 输出文件内容
print(file_contents.decode('utf-8')) # 假设文件是UTF-8编码
#### #法二
def conn_fabric():
# 远程机器信息
host = '10.201.21.24'
user = 'admin'
password = '123'
remote_path = '/c/down/test.txt' # 远程文件路径
# 通过SSH连接到远程服务器
conn = Connection(host=host, user=user, connect_kwargs={"password": password})
# 读取远程文件内容
result = conn.run(f"cat {remote_path}", hide=True)
# 输出文件内容
print(result.stdout)
# 关闭连接
conn.close()
if __name__=='__main__':
param()
conn_fabric()