Python_4-远程连接Linux

使用Python通过SSH自动化Linux主机管理

在系统管理与自动化运维中,SSH(Secure Shell)是一个常用的协议,用于安全地访问远程计算机。Python提供了一个名为paramiko的库,它使得通过SSH进行远程操作变得简单。本文将展示如何使用paramiko库实现远程Linux主机的命令执行和文件上传。

实现python编写代码远程登录linux主机,执行一条命令ls
实现python编写代码远程给linux主机上传一个文件

代码

import paramiko


def ssh_connect_and_execute_command(host, username, password, command):
    """
    连接到SSH服务器并执行命令。

    参数:
    - host: 远程主机的IP地址
    - username: SSH登录用户名
    - password: SSH登录密码
    - command: 要执行的命令

    返回:
    - 命令的输出结果
    """
    # 创建 SSH 客户端并连接
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=host, username=username, password=password)

    # 执行命令
    stdin, stdout, stderr = client.exec_command(command)

    # 获取命令输出和错误信息
    output = stdout.read().decode()
    error = stderr.read().decode()

    # 打印输出和错误信息
    print(output)
    if error:
        print(f"Error: {error}")

    # 关闭连接
    client.close()

    return output


def ssh_connect_and_upload_file(host, username, password, local_path, remote_path):
    """
    连接到SSH服务器并上传文件。

    参数:
    - local_path: 本地文件的路径
    - remote_path: 远程文件的目标路径
    """
    # 创建 SSH 客户端并连接
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=host, username=username, password=password)

    # 上传文件
    sftp = client.open_sftp()
    sftp.put(local_path, remote_path)

    # 关闭SFTP会话
    sftp.close()

    # 关闭SSH连接
    client.close()


# 使用示例
if __name__ == "__main__":
    # Linux 主机信息
    host = "192.168.204.133"
    username = "luruijie"
    password = "********"

    # 执行命令
    command = "ls"
    print("Executing command:", command)
    output = ssh_connect_and_execute_command(host, username, password, command)
    print("Command output:", output)

    # 上传文件
    local_path = "test_remote.txt"
    remote_path = "/home/luruijie/文档/test_remote.txt"
    print("Uploading file from", local_path, "to", remote_path)
    ssh_connect_and_upload_file(host, username, password, local_path, remote_path)

执行ls结果:

执行结果
Linux终端中验证
结果比对

文件传输:

传输文件


安全注意事项

  • 出于安全考虑,不建议在脚本中硬编码密码。考虑使用环境变量或配置文件来存储敏感信息。
  • 使用密钥认证代替密码认证可以提高安全性。
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值