以下是分别用python和php模拟ssh登录远程服务器,执行服务器上脚本的demo:
python版本
import paramiko def sshclient_execmd(hostname, port, username, password, execmd): s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(hostname, port, username, password) stdin, stdout, stderr = s.exec_command(execmd) stdin.write("Y") print stdout.read() s.close() def main(): hostname = '172.1.1.103' #远程服务器ip port = 22 #ssh端口 username = 'root' #ssh登录用户名 password = '123456' #ssh登录密码 execmd = "php /root/1.php" #执行远程服务器上的php文件 sshclient_execmd(hostname, port, username, password, execmd) if __name__ == "__main__": main()
php版
<?php $host = '172.1.1.103'; $port = 22; $user = 'root'; $password = '123456'; $execmd = 'php /root/1.php'; $connection = ssh2_connect($host, $port); if (ssh2_auth_password($connection, $user, $password)) { echo "Authentication Successful!\n"; } else { die('Authentication Failed...'); } $stream = ssh2_exec($connection,$execmd); stream_set_blocking($stream, true); $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); echo stream_get_contents($stream_out);