0

I have logined to a CentOS machine using below Python script:

import paramiko

username = input('Username: ')
password = input('Password: ')

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='192.168.30.129',username=username,password=password,look_for_keys=False)

remote_connection = ssh_client.invoke_shell()
remote_connection.send("mkdir test\n")
remote_connection.send("vi test.txt\n")
remote_connection.send("test\n")
remote_connection.send(":wq\n")
output = remote_connection.recv(65535).decode('ascii')
print (output)

ssh_client.close

What I did with this script:

  1. Login to the CentOS machine using paramiko
  2. Create a folder called 'test'
  3. Create a text file called 'test.txt' using vi and type 'test' in the file.
  4. Type ':wq' in order to save the change I made in 'test.txt' and quit vi.

Step 1 to 3 work perfectly for me, but I couldn't get step 4 done because I don't how to hit "esc" button to enter the Normal Mode of Vi before I'm able to type :wq.

So my question is: How to enter "ESC" key in a Python script?

Parry Wang
  • 115
  • 8

1 Answers1

1

Your question lacks an important step; you need to type Esc before you type :wq. This is just another character, though it's not a printable character; it can be represented e.g. with the hex escape code \x1b (similarly, ctrl-A is \x01, ctrl-B is \x02, etc; Esc is also sometimes represented as ctrl-[.)

However, using vi to create a file programmatically is extremely odd; you're much better off using a simple redirection like

echo "test" >test.txt

If you need to write multiple lines, printf is convenient:

printf '%s\n' 'hello' '' 'world' >test.txt

writes the three lines "hello", an empty line, and "world" to the file.

tripleee
  • 175,061
  • 34
  • 275
  • 318