Fabric 的 connection.forward_local 在超出范围时失败

Fabric's connection.forward_local fails when going out of scope

我正在尝试获取 python 脚本以启用从远程主机到本地计算机的端口转发以访问接口。

如果我手动使用 ssh -L 54321:someotherhost:80 user@host(有密码提示)这很好用,我可以按预期访问 http://localhost:54321/someinterface 上的界面。

现在我正在尝试用 fabric 来做:

from fabric import Connection

HOST = "somehost"
USER = "someuser"
PASSWORD = "somepassword"
LOCAL_PORT = "54321"
REMOTE_PORT = "80"
REMOTE_HOST = "someotherhost"

kwargs = {
    "password": PASSWORD
}
with Connection(HOST, user=USER, connect_kwargs=kwargs).forward_local(
        LOCAL_PORT, REMOTE_PORT, REMOTE_HOST, "localhost"
):
    pass # access interface e.g. via the requests package

但是,1.) 转发似乎不起作用,原因不明和 2.) 当执行 forward_local 范围内的最后一行时,它停止并出现以下错误:

Traceback (most recent call last):
  File ".\path\to\script.py", line 67, in <module>
    main()
  File ".\path\to\script.py", line 35, in main
    pass
  File "C:\Users\ott\AppData\Local\Programs\Python\Python37\lib\contextlib.py", line 119, in __exit__
    next(self.gen)
  File "C:\Users\ott\AppData\Local\Programs\Python\Python37\lib\site-packages\fabric\connection.py", line 883, in forward_local
    raise ThreadException([wrapper])
invoke.exceptions.ThreadException: 
Saw 1 exceptions within threads (TypeError):

Thread args: {}

Traceback (most recent call last):

  File "C:\Users\ott\AppData\Local\Programs\Python\Python37\lib\site-packages\invoke\util.py", line 231, in run
    self._run()

  File "C:\Users\ott\AppData\Local\Programs\Python\Python37\lib\site-packages\fabric\tunnels.py", line 60, in _run
    sock.bind(self.local_address)

TypeError: an integer is required (got type str)

可能 1.) 和 2.) 相关,但我现在关注的是 2.)。我在 forward_local 生成的上下文管理器范围内做什么并不重要,在最后执行的语句停止时。我认为这是由上下文管理器在解释器离开范围时被 python 关闭时引起的。

根据 documentation 参数,如:

  • local_port
  • remote_port

必须是整数而不是字符串。这就是为什么你得到了:

TypeError: an integer is required (got type str)

因此,更改变量:

LOCAL_PORT = "54321"
REMOTE_PORT = "80"

LOCAL_PORT = 54321
REMOTE_PORT = 80

应该可以解决问题。