U 优化对中文输出内容的支持

pull/154/head
vapao 2020-07-18 00:18:46 +08:00
parent a533683af9
commit 7791aefd29
4 changed files with 16 additions and 14 deletions

View File

@ -149,11 +149,7 @@ def valid_ssh(hostname, port, username, password, with_expect=True):
cli = SSH(hostname, port, username, private_key)
if password:
_cli = SSH(hostname, port, username, password=str(password))
code, out = _cli.exec_command('mkdir -p -m 700 ~/.ssh && \
echo %r >> ~/.ssh/authorized_keys && \
chmod 600 ~/.ssh/authorized_keys' % public_key)
if code != 0:
raise Exception(f'add public key error: {out!r}')
_cli.add_public_key(public_key)
try:
cli.ping()
except BadAuthenticationType:

View File

@ -34,9 +34,9 @@ def host_executor(host, pkey, command):
cli = SSH(host.hostname, host.port, host.username, pkey=pkey)
exit_code, out = cli.exec_command(command)
if exit_code == 0:
return True, out.decode() or '检测状态正常'
return True, out or '检测状态正常'
else:
return False, out.decode() or f'退出状态码:{exit_code}'
return False, out or f'退出状态码:{exit_code}'
except Exception as e:
return False, f'异常信息:{e}'

View File

@ -27,7 +27,7 @@ def host_executor(q, host, pkey, command):
try:
cli = SSH(host.hostname, host.port, host.username, pkey=pkey)
exit_code, out = cli.exec_command(command)
out = out.decode() if out else None
out = out if out else None
except AuthenticationException:
out = 'ssh authentication fail'
except socket.error as e:

View File

@ -35,7 +35,7 @@ class SSH:
chmod 600 ~/.ssh/authorized_keys'
code, out = self.exec_command(command)
if code != 0:
raise Exception(out)
raise Exception(f'add public key error: {out}')
def ping(self):
with self:
@ -65,8 +65,8 @@ class SSH:
str_env = ' '.join(f"{k}='{v}'" for k, v in environment.items())
command = f'export {str_env} && {command}'
chan.exec_command(command)
out = chan.makefile("r", -1)
return chan.recv_exit_status(), out.read()
stdout = chan.makefile("rb", -1)
return chan.recv_exit_status(), self._decode(stdout.read())
def exec_command_with_stream(self, command, timeout=1800, environment=None):
command = 'set -e\n' + command
@ -78,12 +78,12 @@ class SSH:
str_env = ' '.join(f"{k}='{v}'" for k, v in environment.items())
command = f'export {str_env} && {command}'
chan.exec_command(command)
stdout = chan.makefile("r", -1)
stdout = chan.makefile("rb", -1)
out = stdout.readline()
while out:
yield chan.exit_status, out
yield chan.exit_status, self._decode(out)
out = stdout.readline()
yield chan.recv_exit_status(), out
yield chan.recv_exit_status(), self._decode(out)
def put_file_by_fl(self, fl, remote_path, callback=None):
with self as cli:
@ -100,6 +100,12 @@ class SSH:
sftp = cli.open_sftp()
sftp.remove(path)
def _decode(self, out: bytes):
try:
return out.decode()
except UnicodeDecodeError:
return out.decode('GBK')
def __enter__(self):
if self.client is not None:
raise RuntimeError('Already connected')