以下のPythonスクリプトを手動でプロンプトから実行しファイルにリダイレクトした場合とcron経由で実行・標準出力及び標準エラー出力をファイルリダイレクトで出力される内容が異なってしまいます。Cron経由の場合出力されないのは、以下1番のケースのみで、関数内に記述されているPrint文となりますが、2番のPrint文は問題なく出力されます。
プロンプトから以下の様に手動実行した場合は両方のPrint文がファイルに出力されます。解決策ご存知の方、どうぞご教授頂ければ幸いです。
python /CR/script_v1.py > /Backup/result.log
1.Cronからリダイレクト時出力されるプリント文:
print('## %s SSH connection failed ##' % h + '\n')
2.Cronからリダイレクト時出力されないプリント文:
print("IP: {0} :({1}):".format(h, c) + '\n')
cron内容
PATH=/root/anaconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/bin/bash
0,10 * * * * python /CR/script_v1.py > /Backup/result.log 2>&1
#Modules import paramiko from contextlib import suppress from paramiko import SSHException #Variables USER = 'sssr' PSWD = '#pdddddt' #Classes and Functions class InputReader: def __init__(self, commands_path, hosts_path): self.commands_path = commands_path self.hosts_path = hosts_path def read(self): self.commands = self.__readlines(self.commands_path) self.hosts = self.__readlines(self.hosts_path) def __readlines(self, path): with open(path) as f: # return map(lambda v: v.strip(), f.readlines()) return [v.strip() for v in f.readlines()] #List comprehension class CommandExecuter: def __init__(self, host, command): self.host = host self.command = command def execute(self): with suppress(TimeoutError): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.host, username=USER, password=PSWD) stdin, stdout, stderr = ssh.exec_command(self.command) errors = stderr.readlines() lines = [v.strip() for v in stdout.readlines()] return lines print('## %s SSH connection failed ##' % h + '\n') #Main Procedure if __name__ == '__main__': reader = InputReader("commands2.txt", "systems2.txt") reader.read() for h in reader.hosts: for c in reader.commands: executer = CommandExecuter(h, c) results = executer.execute() print("IP: {0} :({1}):".format(h, c) + '\n') if results != None: for i in results: print(i + '\n')
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/19 17:17
2017/12/20 03:20