#python #exception #ssh #paramiko
Вопрос:
У меня на ноутбуке есть код python, с помощью которого paramiko отправляет команды через ssh на удаленный RPi. Я хочу запустить 2 скрипта на python:
- create.py : чтобы создать небольшой файл json conf на RPi
- set.py : чтобы обновить этот файл conf
код парамико:
import paramiko
server = "192.168.1.94"
username = "..."
password = "..."
cmd_to_execute = 'cd argparse/; python create.py; python set.py -i test; cat sensor.conf'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, port=22, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)
print(" ".join(ssh_stdout.readlines()))
ssh.close()
В set.py файл, я использовал argparse, чтобы вручную настроить файл conf и разрешить что-то вроде:
python set.py -i 10.10.10.10 -s 2 -r 0
create.py:
import os
path = "sensor.conf"
with open(path, 'w') as f:
f.write('{"ip": null, "room_id": null, "sensor_id": null}')
set.py файл:
import argparse
import ipaddress
import json
path = "sensor.conf"
parser = argparse.ArgumentParser(description='Set fields in sensor config file.')
parser.add_argument('-i', '--ip', help='Sensor IP as string (xxx.xxx.xxx.xxx)')
parser.add_argument('-r', '--room', type=int, help='Sensor room ID (integer from server)')
parser.add_argument('-s', '--sensor', type=int, help='Sensor ID (integer from server)')
args = parser.parse_args()
with open(path, 'r') as f:
data = json.load(f)
if args.ip:
try:
ipaddress.IPv4Network(args.ip)
data['ip'] = args.ip
except Exception as e:
print(e)
if args.room or args.room == 0:
data['room_id'] = args.room
if args.sensor or args.sensor == 0:
data['sensor_id'] = args.sensor
with open(path, 'w') as f:
json.dump(data, f)
print(data)
I use ipaddress.IPv4Network() as a way to ensure the IP given is well formatted, within a try/except scope.
When I am manually connected to my RPi with ssh, and try python set.py -i test
I do have an exception handled and nothing is written in my file.
But with paramiko, the exception seems to not be handled or not even occurring? because my file contains «test» in the ‘ip’ field.
EDIT
I found a better way to check for a correct IP, and it fixed the problem with paramiko: I replaced the try/except with a function that returns True/False if the string follows the format of an IP address.
I still don’t understand why this happened with the try/except, any idea?
Many thanks