咨询热线:4006-75-4006
售前:9:00-23:30 备案:9:00-18:00 技术:7*24h
以下是分别用python和php模拟ssh登录远程服务器,执行服务器上脚本的demo:
python版本
import paramikodef 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' #远程服务器ipport = 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! ";} 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);