Information About SSH Multiple Connections Using pexpect

Asked 2 years ago, Updated 2 years ago, 42 views

I am a beginner at python and linux.I want to use pexpect to connect multiple times with ssh, but it doesn't work.

The steps you would like to take are as follows.
1. SSH connection from terminal A to terminal B
2. SSH connection from terminal B to terminal A
Disconnect SSH connection in 3.2
Lost SSH Connection in 4.1

Terminal A (mac python 3.5.1pect 4.2.1)
Terminal B (ubuntupython 3.5.1+pexpect 4.2.1)

Here is the code.
a_method1.py

import expect
defa_method1():
    p=pexpect.spawn('sshb_ip_addr')
    p.expect('ssword:*')
    p.sendline('passwd')
    p.sendline('python3/b_path/b_method.py')
    p.sendline('exit')
    p.interact()
if__name__=='__main__':
    a_method1()

b_method.py

import expect
defb_method():
    p=pexpect.spawn('ssha_ip_addr')
    p.expect('ssword:*')
    p.sendline(passwd)
    p.sendline('python3/a_path/a_method2.py')
    p.sendline('exit')
    p.interact()
if__name__=='__main__':
    b_method()

a_method2.py

defa_method2():
    pass
if__name__=='__main__':
    a_method2()

The results are as follows:

$python3a_method.py

python3/b_path/b_method.py
exit
python3/b_path/b_method.py
exit
Welcome to Ubuntu Information

 * Documentation: https://help.ubuntu.com/

999 packages can be updated.
999 updates are security updates.

Last login—from a_ip_addr
B terminal: ~$python3/b_path/b_method.py
B terminal: ~$exit
logout
Connection to b_ip_addr closed.
A terminal: ~a_user$

That's all, thank you for your cooperation.

python linux

2022-09-30 18:55

1 Answers

This is probably because you are sending commands in p.sendline without waiting for the login prompt. Try adding a p.expect statement that waits for the prompt before p.sendline

Example: ExPlease change the Expect pattern according to your environment.

import expect
defa_method1():
    p=pexpect.spawn('sshb_ip_addr')
    p.expect('ssword:*')
    p.sendline('passwd')
    p.expect('$')<- Wait for prompt
    p.sendline('python3/b_path/b_method.py')
    p.expect('$')<- Wait for prompt
    p.sendline('exit')
    p.interact()
if__name__=='__main__':
    a_method1()


2022-09-30 18:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.