Auto-login with password and guest management via ssh using expect

    Once again, using this script in one of the training classes, I looked for materials and found that they had not remembered expect here for a long time. This is a great alternative command line interpreter for Linux, which can communicate with it instead of a living person, and I will add here only one more example of its application.



    There aren’t any particular pictures on this subject, and there won’t be any pictures in the article at all, therefore we will draw your attention to the cover of a wonderful book


    A bit of history and offtopic


    At the beginning of 2013, I returned to additional education for children, received 24 hours of weekly workload for four groups of “young programmers” and “young system administrators”, and proceeded to recruit students at two sites: my own office and the computer science office of a nearby gymnasium. Through the efforts of the “young system administrators” groups, we put our office in order by deploying AltLinux 6 and a couple of alternative distributions. And in the gymnasium, a very experienced "computer class engineer" had long been conducting experiments with source-based, which ended with the arrival of Calculate Linux on all machines of teachers and classrooms. Respect to him)

    Task


    After a couple of months of classes, I saw a problem. Children refused to leave classes, trying in any way to stay longer. Because pedagogical technology is not mine, but we still have a technical circle, I killed third-party processes and turned off machines via ssh. This increased student interest in exploring command line capabilities. However, they soon found a bug: shutting down with “hands” takes too much time, and even in a small office they will have time to restart half of the machines before I complete the punitive process, and this will drag out the matter. To demonstrate who is the main best programming feature for the command line, I thought about automation.

    Solution options


    The zero thought was to use italc , and we even spent several weeks setting it up and experimenting. But it turned out to be too glitchy and primitive, therefore it was safely forgotten.

    The first thought was to configure access via ssh by fingerprint. This would reduce the task to one cycle, but for application “on the knee” this method was not quite suitable (although why not? EMNIP, a fingerprint for the user can also be created without root). But with an accessible password authorization (by the way, a big security risk for classrooms where login passwords are the same), I was interested in the option with automatic password authorization. After spending an hour searching, I found some examples for expect.

    Solution via expect


    Before the start

    But, firstly, it must be installed. In my class, we easily did this, but in the gymnasium class SUDDENLY it turned out that expect, and nmap, and some other interesting system utilities were not only installed, but also available to the student. This helped us a lot when once again the NFS-mounted network drive “dropped” and we found a way to distribute tasks through a quickly found accounting computer with shared drives.

    Secondly, in addition to expect itself, we will need to use 2 types of cycle: with a precondition and with a parameter. The first is necessary for the "looping" of the process so that you can hang the script execution in the background for the entire lesson. The second is necessary to sort through the necessary addresses, which we will go to via ssh using actually expect.

    It is also necessary to remember that, by default, the script fails when the first error occurs, for example, the client computer does not respond, and you should probably look for a way to handle such exceptions.

    Script

    We inform that for execution we need to use a non-standard interpreter
    #!/usr/bin/expect -f
    


    We set a pause to wait for a response from the client, username and password (this is more likely by inertia from the examples available on the network):

    set timeout 2
    set USER "u1"
    set PASS "1"
    


    Beginning of the script:
    while 1 {   // применение цикла с предусловием 
    foreach HOST {58 60 61} {     // применение цикла с параметром для списка окончаний адресов. Да, их можно генерировать и автоматически, но пост не об этом
    spawn ssh $USER@192.168.0.$HOST // подключаемся
      expect {
      "(yes/no)?*" {
      send "yes\r" // не забывайте про \r в конце строки, перед кавычками. Иначе волшебства не получится
     }
      }
       expect "word:"
      send "$PASS\r"
      expect "$*"
      send "killall -r teew*\r"
      expect "$*"
      send "killall firefox\r"
      expect "$*"
      send "killall chrome\r"
      expect "$*"
      send "exit\r"
      expect eof
     }
    


    It was a simple auto-kill script for unnecessary processes for a gymnasium. In my own office, I modified the script to automatically turn off the machines:

    guest@0-315-gymn2 ~ $ cat scripty 
    #!/usr/bin/expect -f
    set timeout 2
    set USER "user"
    set HOST "2"
    set PASS "2357"
    # Начало сценария
     while 1 {
     foreach HOST {2 3 5 7} { 
      spawn ssh $USER@192.168.0.$HOST
      expect {
      "(yes/no)?*" {
      send "yes\r"
      }
      } 
      expect "word:"
      send "$PASS\r"
      expect "$*"
      send "su\r"
      expect "word:*"
      send "supassword\r"
      expect "#*"
      send "/sbin/shutdown 0 -hP\r"
      expect "#*"
      send "exit\r"
      expect "$*"
      send "exit\r"
      expect eof
     }
     }
    


    Conclusion


    I hope that the mention of the wonderful expect interpreter and a couple of live examples of working with it will be useful to the community and will generate many articles about its more subtle applications.

    PS:


    The script for auto-searching active computers and creating a list of addresses for processing was written a little later by one of my students (not to do everything interesting for yourself). A little later, when he deserves an invite, he will be able to write about it himself as applied to a more interesting task.

    Also popular now: