python执行Linux命令
Linux命令执行方法函数封装:
本地执行命令:
def exe_cmd(cmd): p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: next_line = p.stdout.readline() return_line = next_line.decode("utf-8", "ignore") if return_line == '' and p.poll() != None: break print(return_line) stdout, stderr = p.communicate() if p.returncode != 0: return False return True
paramiko远程执行,字符串返回方式:
class SSH: def __init__(self, hostname, port, username, password): self.c = paramiko.SSHClient() self.c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.c.connect(hostname, port, username, password, timeout=80) def __del__(self): self.c.close() def exec_cmd(self, command, print2=False): stdin, stdout, stderr = self.c.exec_command(command) return stdout.readlines()
paramiko远程执行,实时标准输出:
class SSH: def __init__(self, hostname, port, username, password): self.c = paramiko.SSHClient() self.c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.c.connect(hostname, port, username, password, timeout=80) def __del__(self): self.c.close() def exec_cmd(self, command, print2=False): stdin, stdout, stderr = self.c.exec_command(command) while True: line = stdout.readline() if not line: break print(line)