python devops / paramiko ssh / paramiko sftp

s

http://www.paramiko.org , A Python implementation of SSHv2.

[root@tc ~]$ pip install paramiko http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com   # linux开发环境安装相关软件包

- python ssh

复制代码
import paramiko

# SSH服务器的信息
hostname = 'your_server_hostname_or_ip'
port = 22  # 默认SSH端口是22
username = 'your_username'
password = 'your_password'  # 或者你可以使用密钥进行身份验证

# 创建SSH客户端
ssh_client = paramiko.SSHClient()

# 自动添加主机密钥 (不建议在生产中使用,应该验证主机密钥)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    # 连接到SSH服务器
    ssh_client.connect(hostname, port, username, password)

    # 执行命令
    command = 'ls -l'  # 你可以替换为任何你想执行的命令
    stdin, stdout, stderr = ssh_client.exec_command(command)

    # 输出命令执行结果
    print("Command Output:")
    for line in stdout.readlines():
        print(line.strip())

    # 关闭SSH连接
    ssh_client.close()

except paramiko.AuthenticationException:
    print("Authentication failed, please check your credentials.")
except paramiko.SSHException as e:
    print(f"SSH error: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # 关闭SSH客户端连接
    ssh_client.close()
复制代码

- python sftp

复制代码
import paramiko

# SSH服务器的信息
hostname = 'your_server_hostname_or_ip'
port = 22  # 默认SSH端口是22
username = 'your_username'
password = 'your_password'  # 或者你可以使用密钥进行身份验证

# 远程和本地文件路径
remote_path = '/path/to/remote/file.txt'
local_path = '/path/to/local/file.txt'

# 创建SSH客户端
ssh_client = paramiko.SSHClient()

# 自动添加主机密钥 (不建议在生产中使用,应该验证主机密钥)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    # 连接到SSH服务器
    ssh_client.connect(hostname, port, username, password)

    # 创建SFTP客户端
    sftp = ssh_client.open_sftp()

    # 从远程服务器下载文件到本地
    sftp.get(remote_path, local_path)
    print(f"Downloaded {remote_path} to {local_path}")

    # 上传本地文件到远程服务器
    sftp.put(local_path, remote_path)
    print(f"Uploaded {local_path} to {remote_path}")

    # 关闭SFTP客户端
    sftp.close()

except paramiko.AuthenticationException:
    print("Authentication failed, please check your credentials.")
except paramiko.SSHException as e:
    print(f"SSH error: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # 关闭SSH客户端连接
    ssh_client.close()
复制代码

 

 

end

posted @   siemens800  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示