要在远程服务器上运行Python代码,可以采用以下方法:
ssh username@remote_server_ip
python /path/to/script.py
from fabric import Connection
# 连接到远程服务器
c = Connection(host='remote_server_ip', user='username', connect_kwargs={'password': 'password'})
# 在远程服务器上运行Python脚本
result = c.run('python /path/to/script.py')
print(result.stdout)
import paramiko
# 创建SSH客户端
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接到远程服务器
client.connect('remote_server_ip', username='username', password='password')
# 执行命令
stdin, stdout, stderr = client.exec_command('python /path/to/script.py')
# 输出结果
print(stdout.read().decode())
# 关闭连接
client.close()
这些方法可以帮助您在远程服务器上运行Python代码,并获取运行结果。您需要根据实际情况选择适合您的方法,并替换示例代码中的用户名、密码、远程服务器IP和脚本路径。