-
Notifications
You must be signed in to change notification settings - Fork 58
Description
I'm working on a way to turn on and off my PoE ports on my Unifi switch. I found the script below, which works if I run it standalone.
`
import telnetlib
import re
def powercycle(ip, username, password, interfaces):
tn = telnetlib.Telnet(ip)
def encode(s):
return s.encode('utf-8')
def write_line_and_read_until(cmd, expected):
tn.write(encode(cmd + "\n"))
tn.read_until(encode(expected))
def write_line_and_expect(cmd, expect, timeout=1):
tn.write(encode(cmd + "\n"))
tn.expect(expect, timeout)
tn.read_until(encode("User:"))
write_line_and_read_until(username, "Password:")
write_line_and_expect(password, [re.compile(encode(".*>"))])
write_line_and_read_until("en", "Password:")
write_line_and_expect(password, [re.compile(encode(".*#"))])
write_line_and_expect("config", [re.compile(encode("\(Config\)#"))])
for intf in interfaces:
print("Cycling intf {}".format(intf))
r = re.compile(encode("\(Interface {}\)#".format(intf)))
write_line_and_expect("Interface {}".format(intf), [r])
write_line_and_expect("poe opmode shutdown", [r])
write_line_and_expect("poe opmode auto", [r])
write_line_and_expect("exit", [re.compile(encode("\(Config\)#"))])
write_line_and_expect("exit", [re.compile(encode(".*#"))])
write_line_and_expect("exit", [re.compile(encode(".*>"))])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Power cycle UBNT POE port.')
parser.add_argument('--username', type=str, required=True)
parser.add_argument('--password', type=str, required=True)
parser.add_argument('--ip', type=str, required=True)
parser.add_argument('--interfaces', type=str, required=True, nargs="+")
args = parser.parse_args()
powercycle(args.ip, args.username, args.password, args.interfaces)
`
However, when I add the @service tag and load it through the Services tab in Home Assistant and run it, like this:
it raises the following error:
Exception in <file.edgemax_poe.powercycle> line 19: tn.expect(expect, timeout) ^ TypeError: 'str' object does not support item assignment
I don't see the problem here. I suspect the 'interfaces' argument is causing problems here, because I do see a telnet session being started on the switch. Apparently, the 'expect' argument being passed, is a 'str' while it shoudl be a list. Not sure why that is happening when executing this in PyScript.
Any ideas what I'm overlooking? Much appreciated.
