亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過 ssh 有條件地運行子進程,同時將輸出附加到(可能是遠程)文件

通過 ssh 有條件地運行子進程,同時將輸出附加到(可能是遠程)文件

隔江千里 2023-07-11 15:12:10
我有一個可以在我的主機和其他幾臺服務器上運行的腳本。我想使用 ssh 將此腳本作為我的主機上的后臺進程與遠程計算機一起啟動,并將 stdout/stderr 輸出到主機以用于我的主機后臺進程,并輸出到遠程計算機以用于遠程計算機后臺任務。我嘗試過subprocess.check_output(['python'?,'script.py'?,'arg_1',?'?>?file.log?',?'?&?echo?-ne?$!?']但它不起作用。它不給我 pid 也不寫入文件。它可以工作shell=True,但后來我讀到出于安全原因使用 shell=True 不好。然后我嘗試了p?=?subprocess.Popen(['python'?,'script.py'?,'arg_1',?'?>?file.log?']現在我可以獲得進程 pid,但輸出沒有寫入遠程日志文件。使用下面建議的 stdout/stderr 參數將在我的主機而不是遠程計算機中打開日志文件。有人可以建議我一個既可以在我的主機上工作,也可以通過 ssh 連接到遠程服務器并在那里啟動后臺進程的命令嗎?并寫入輸出文件?<HOW_TO_GET_PID>?=?subprocess.<WHAT>(?([]?if?'localhost'?else?['ssh','<remote_server>'])?+?['python',?'script.py',?'arg_1'?<WHAT>]?)有人可以完成上面的偽代碼嗎?
查看完整描述

2 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

你不可能在一行行中得到安全、正確的東西而不使其不可讀。最好不要嘗試。


請注意,我們在這里使用 shell:在本地情況下,我們顯式調用shell=True,而在遠程情況下ssh,總是隱式啟動 shell。


import shlex

import subprocess


def startBackgroundCommand(argv, outputFile, remoteHost=None, andGetPID=False):

    cmd_str = ' '.join(shlex.quote(word) for word in argv)

    if outputFile != None:

        cmd_str += ' >%s' % (shlex.quote(outputFile),)

    if andGetPID:

        cmd_str += ' & echo "$!"'

    if remoteHost != None:

        p = subprocess.Popen(['ssh', remoteHost, cmd_str], stdout=subprocess.PIPE)

    else:

        p = subprocess.Popen(cmd_str, stdout=subprocess.PIPE, shell=True)

    return p.communicate()[0]


# Run your command locally

startBackgroundCommand(['python', 'script.py', 'arg_1'],

    outputFile='file.log', andGetPID=True)


# Or run your command remotely

startBackgroundCommand(['python', 'script.py', 'arg_1'],

    remoteHost='foo.example.com', outputFile='file.log', andGetPID=True)


查看完整回答
反對 回復 2023-07-11
?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

# At the beginning you can even program automatic daemonizing

# Using os.fork(), otherwise, you run it with something like:

# nohup python run_my_script.py &

# This will ensure that it continues running even if SSH connection breaks.

from subprocess import Popen, PIPE, STDOUT


p = Popen(["python", "yourscript.py"], stdout=PIPE, stderr=STDOUT, stdin=PIPE)

p.stdin.close()

log = open("logfile.log", "wb")

log.write(b"PID: %i\n\n" % p.pid)

while 1:

    line = p.stdout.readline()

    if not line: break

    log.write(line)

    log.flush()


p.stdout.close()

log.write(b"\nExit status: %i" % p.poll())

log.close()


查看完整回答
反對 回復 2023-07-11
  • 2 回答
  • 0 關注
  • 267 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號