繁体   English   中英

无法在 python 子进程中使用 gcloud compute ssh 命令

[英]Cannot use gcloud compute ssh command in python subprocess

我已经设置了一个计算引擎,我可以在命令提示符下使用 ssh 命令,比如

gcloud compute ssh test-instance@cloud-engine-noapi --zone us-central1-f --command "rm -f test.txt"

并成功删除服务器中的test.txt。

但是,当我在 python 中调用这些时。

subprocess.call(['gcloud', 'compute', '--project', 'test-project','ssh', temp_instance, '--zone', zone, '--command', '"cd /home"'], shell=True)
subprocess.call(['gcloud', 'compute', '--project', 'test-project','ssh', temp_instance, '--zone', zone, '--command', '"ls -l"'], shell=True)
subprocess.call(['gcloud', 'compute', '--project', 'test-project','ssh', temp_instance, '--zone', zone, '--command', '"rm -f /home/test.txt"'], shell=True)

回报总是像

bash: /command : No such file or directory

和像ls这样的命令

bash: /command : command not found

有什么我必须先做的过程吗?

虽然,可能没有人遇到这个问题...但是我终于想出了一种解决方法。

由于仅在使用子进程时才会出现问题,因此我通过编写(bat / sh)文件暂时保存命令来绕过它。

喜欢,

with open(os.path.join(__location__, 'gcloud_command.bat'), 'w') as bat:
            command_arr = []
            for instance in all_instances_name:
                temp_instance = user_name + "@" + instance
                temp_file_path = '/home/' + user_name + '/'
                command_arr.append('call gcloud compute ssh ' + temp_instance + ' --zone ' + zone + ' --command "cd ' + temp_file_path + '; rm -rf ' + temp_file_path + projectname.split('.')[0] + '; rm -f ' + temp_file_path + projectname.split('.')[0] + '*"\n')
                command_arr.append('call gcloud compute scp "' + fullpath_projectname + '" ' + instance + ':' + temp_file_path + '\n')
                if is_zip:
                    command_arr.append('call gcloud compute ssh ' + temp_instance + ' --zone ' + zone + ' ' + ' --command "cd ' + temp_file_path + '; unzip ' + temp_file_path + projectname + '"' + '\n')
            bat.writelines(command_arr)

并执行

subprocess.Popen(os.path.join(__location__, 'gcloud_command.bat'))

我知道这已经很老了,但我花了一些时间才弄明白。 在我的例子中,帮助避免了双引号(尽管 gcloud cli help 推荐它)。

例子:

subprocess.call(['gcloud', 'compute', f'--project={test-project}','ssh', temp_instance, f'--zone={zone}, '--command=cd /home'], shell=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM