Last active
July 13, 2023 08:39
-
-
Save qiuchengxuan/784b619b228be6f7c344af7d09cb8aeb to your computer and use it in GitHub Desktop.
Access HUAWEI Switch via CLI with python script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys | |
_, ip, user, passwd = sys.argv | |
CLI_PROMPT = r'[\[<][^>\]]+[\]>]' | |
ssh = spawn('ssh %s@%s' % (username, ip)) | |
if not ssh: | |
return | |
ssh.expect('password') | |
while True: | |
index = ssh.expect([r'\[Y/N\]', HuaweiSwitch.CLI_PROMPT, | |
EOF, TIMEOUT], 1) | |
if index > 1: | |
return None | |
elif index == 1: | |
break | |
ssh.sendline('N') # whatever it says, say no | |
ssh.sendline(passwd) | |
def cli(cmd): | |
# NOTE: Add '| no-more' if output may too long | |
if not ssh: | |
err = 'SSH not connected on switch %s' % ip | |
LOG.error(err) | |
return False, err | |
sync = '# %s' % str(time()) | |
ssh.sendline(sync) | |
ssh.expect(sync) | |
ssh.sendline(cmd) | |
ssh.expect(cmd.replace('|', r'\|')) | |
ssh.expect(HuaweiSwitch.USER_VIEW_PROMPT) | |
return True, ssh.before.replace('\r', '').strip('\n') | |
def cli_config(cmd): | |
if not ssh: | |
err = 'SSH not connected on switch %s' % ip | |
LOG.error(err) | |
return False, err | |
if isinstance(cmd, list): | |
cmd = '\n'.join(cmd) | |
ssh.sendline('system-view') | |
ssh.expect(HuaweiSwitch.SYSTEM_VIEW_PROMPT) | |
ssh.sendline(cmd) | |
ssh.sendline(chr(26)) # CTRL+Z, back to user view | |
index = ssh.expect([HuaweiSwitch.USER_VIEW_PROMPT, | |
HuaweiSwitch.COMMIT_PROMPT]) | |
if index == 1: | |
ssh.sendline('Y') | |
output = ssh.before.replace('\r', '').strip('\n') | |
return True, output | |
return True, ssh.before.replace('\r', '').strip('\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment