赞
踩
ssh远程到其他机器上执行多条命令时,遇到有的命令不会执行成功,起初以为是远程过去执行命令的权限不够,不是以root用户的权限执行命令,所以在命令前加了sudo,发现依然不能全部执行成功,下面是最初执行的代码:
- definstall_pkg(ip_list, copy_file_path, copy_to_path, cada_env_name):for pkg_ip in ip_list:
- print("pkg install on: ", pkg_ip)
- cmd = ""
- cmd += f"scp -r {copy_file_path} root@{pkg_ip}:{copy_to_path}; "
- print("cmd: ", cmd)
- os.system(cmd)
- print("Copy file complete!")
- time.sleep(2)
- ssh_remote = paramiko.SSHClient()
- ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh_remote.connect(hostname=pkg_ip,
- port=22,
- username=username,
- password=password)
-
- remote_cmd = ""
- remote_cmd += f"cp -r {copy_to_path}/{cada_env_name} /root/miniconda3/envs/; "
- remote_cmd += f"cd /root/miniconda3/envs/; "
- remote_cmd += f"tar -vxf {cada_env_name}; "
- print("install whl cmd is : ", remote_cmd)
- try:
- stdin, stdout, stderr = ssh_remote.exec_command(remote_cmd)
- print(stdout.readlines())
- except Exception as e:
- print("if exception is timeout, that's fine")
- print("exception is : ", e)
- finally:
- ssh_remote.close()
- print("install pkg on : ", pkg_ip)复制
上面这段代码执行的时候,不会执行最后一个解压命令:tar -vxf {cada_env_name};这个命令单执行的时候,文件解压会需要很长的时间。原因是由于如果直接写的话在每条命令后加分号执行时会报错,如果不加分号,分一条命令一条命令地执行,起不到作用,如切换路径等。经过百度,我在ssh的时候添加了look_for_keys=True和调用exec_command的时候加了get_pty=True就可以以成功执行所有命令了。下面是修改后的代码:
- definstall_pkg(ip_list, copy_file_path, copy_to_path, cada_env_name):for pkg_ip in ip_list:
- print("pkg install on: ", pkg_ip)
- cmd = ""
- cmd += f"scp -r {copy_file_path} root@{pkg_ip}:{copy_to_path}; "
- print("cmd: ", cmd)
- os.system(cmd)
- print("Copy file complete!")
- time.sleep(2)
- ssh_remote = paramiko.SSHClient()
- ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh_remote.connect(hostname=pkg_ip,
- port=22,
- username=username,
- password=password,
- look_for_keys=True)
-
- remote_cmd = ""
- remote_cmd += f"cp -r {copy_to_path}/{cada_env_name} /root/miniconda3/envs/; "
- remote_cmd += f"cd /root/miniconda3/envs/; "
- remote_cmd += f"tar -vxf {cada_env_name}; "
- print("install whl cmd is : ", remote_cmd)
- try:
- stdin, stdout, stderr = ssh_remote.exec_command(remote_cmd, get_pty=True)
- print(stdout.readlines())
- except Exception as e:
- print("if exception is timeout, that's fine")
- print("exception is : ", e)
- finally:
- ssh_remote.close()
- print("install pkg on : ", pkg_ip)复制
关于这个两个参数的使用,百度以下说明仅供参考:
look_for_keys(bool类型): 默认为True,就是会找你 .ssh 目录下有没有合适的密钥文件;
get_pty(bool类型):实际在远程执行sudo命令时,一般主机都会需要通过tty才能执行,通过把get_pty值设置为True,可以模拟tty;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。