I am using Netmiko to automate file transfer via SCP on a Huawei device. The SSH connection works fine, and I can send commands in system-view
mode. However, when the SCP command runs, it prompts for a password, but the password is not being sent correctly, causing a timeout.
Here is my current code:
import ncs
import _ncs
from ncs.application import Service
from ncs.dp import Action
import time
import datetime
import os
from netmiko import ConnectHandler
class DoubleAction(Action):
@Action.action
def cb_action(self, uinfo, name, kp, input, output, trans):
self.log.info('action name: ', name)
root = ncs.maagic.get_root(trans, shared=False)
device = root.devices.device[input.device]
self.log.info('hostname: ', device.name)
_ncs.dp.action_set_timeout(uinfo, 30 * 60)
device_name = input.device
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
log_file_name = f"package-{device_name}-{timestamp}.log"
log_file_path = os.path.join('/var/log/ncs', log_file_name)
if 'tailf-ned-huawei-vrp-stats' in [mod.name for mod in device.live_status.yanglib__modules_state.module]:
device_params = {
'device_type': 'huawei',
'host': 'DEVICE_IP',
'username': 'USERNAME',
'password': 'PASSWORD',
}
net_connect = ConnectHandler(**device_params)
commands = []
if input.delete_archives:
commands.extend([
'delete /unreserved cfcard:/logfile/diaglog*.zip all',
'delete /unreserved cfcard:/KPISTAT/2023*.* all',
'reset recycle-bin /f',
])
scp_command = f'scp -i LoopBack0 {input.user_name}@{input.ip}:{input.path_server} cfcard:/'
commands.append(scp_command)
result_list = []
errors = []
try:
output = net_connect.send_command_timing('system-view', strip_command=False, strip_prompt=False)
self.log.info(f'Output após system-view: {output}')
for command in commands:
self.log.info(f'Rodando o comando: {command}')
output = net_connect.send_command_timing(command, strip_command=False, strip_prompt=False)
self.log.info(f'Output do comando {command}: {output}')
if "password:" in output:
self.log.info("Senha solicitada, enviando senha...")
net_connect.write_channel(input.password + 'n')
output += net_connect.read_channel()
self.log.info(f'Output após enviar senha: {output}')
result_list.append(output)
time.sleep(1)
net_connect.disconnect()
except Exception as e:
errors.append(f"Error executing {command}: {str(e)}")
self.log.error(f"Error executing {command}: {str(e)}")
with open(log_file_path, 'a') as log_file:
log_file.write(f"Output for device {device_name} at {timestamp}:n")
for command, output in zip(commands, result_list):
log_file.write(f"Comando executado: {command}n")
log_file.write(f"Saída do comando: {output}n")
log_file.write("Output final:n")
if errors:
log_file.write("Erros encontrados:n")
for error in errors:
log_file.write(error + "n")
else:
self.log.warning(f"O dispositivo {input.device} não suporta os comandos necessários.")
return
Log output:
<INFO> Output do comando scp -i LoopBack0 root@FTP_IP:FILE_PATH cfcard:/: scp -i LoopBack0 root@FTP_IP:FILE_PATH cfcard:/
Trying FTP_IP ...
Press CTRL+K to abort
Connected to FTP_IP ...
Enter password:
<INFO> Senha solicitada, enviando senha...
<DEBUG> write_channel: b'PASSWORDn'
<DEBUG> read_channel:
I’ve tried using send_command_timing
and write_channel
to send the password, but it doesn’t seem to be recognized by the SCP command. Any help on how to properly send the password for the SCP command using Netmiko would be greatly appreciated. Thank you!
user25980565 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.