import paramiko


def execute_command_on_linux(host, port, username, password, command):
    try:
        # 创建 SSH 对象
        ssh = paramiko.SSHClient()
        # 允许连接不在 know_hosts 文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接服务器
        ssh.connect(hostname=host, port=port, username=username, password=password)
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 获取命令结果
        result = stdout.read().decode()
        # 获取错误信息
        error = stderr.read().decode()
        if error:
            print(f"执行命令时出现错误: {error}")
        # 关闭连接
        ssh.close()
        return result
    except Exception as e:
        print(f"连接或执行命令时出现异常: {e}")
        return None


if __name__ == "__main__":
    # 配置 Linux 服务器信息
    host = '119.29.146.254'
    port = 22
    username = 'root'
    password = 'zrd1236987!'
    # 要执行的命令
    command = 'du -sh /home/*'

    result = execute_command_on_linux(host, port, username, password, command)
    if result:
        print("命令执行结果:")
        print(result)
