From: Ken I. <fn...@ua...> - 2009-01-02 22:08:53
|
On Fri, Jan 02, 2009 at 01:53:09PM -0700, Dave Donohue wrote: > Hey guys, I'm having some problems figuring out how to accomplish the below. > I'll forwarn i'm slightly newer to expect, i understand how to use it to do > what i want on a machine, but i've never done things on the local machine mid > stream and not even sure if it's doable while having a working spawn'd > connection up and running. > > I'm trying to create directories on a remote machine by using ssh. What i > want to do is something like below. > > > sub CreateAdditionalDirectories { > > foreach $line(@servers) { > > $command = "ssh $username\@$line"; > > my $exp1 = Expect->spawn($command) > or die "Cannot spawn $command: #!\n"; > @match_patterns = ("Password"); > $patidx = $exp1->expect($timeout, @match_patterns); > $exp1->send("$password\r"); > > foreach $createdirectories(@createdirectories) { > > @match_patterns = ("bash"); > $patidx = $exp1->expect($timeout, @match_patterns); > $exp1->send("/usr/local/bin/sudo mkdir $HOMEDIR/$createme/incoming/$directory\ > r"); > @match_patterns = ("bash"); > $patidx = $exp1->expect($timeout, @match_patterns); > $exp1->send("/usr/local/bin/sudo mkdir $HOMEDIR/$createme/pub/$directory\r"); > @match_patterns = ("bash"); > $patidx = $exp1->expect($timeout, @match_patterns); > }; > }; > }; > > Is the above doable? basically i want to prevent establishing multipul ssh > connections to the machine if i don't have to. Is their a way to spawn ssh > connection, then come back to just normal perl and evaluate a variable, then > act based on that variable? The purpose of expect is pretty much to do just that, to allow automating interactive processes/sessions. Your spawned ssh session persists in a process which you interact with via fifos, and can last as long as you want it to. I can't easily follow the code; maybe the formatting/indentation is lost to my mail reader; and wouldn't $server be clearer than $line? Whatever you're doing, it would likely be trivial to do in a local script if you simply set up ssh keys on the hosts and authenticate locally. If you're dealing with several servers it would be something well worth figuring out, IMHO. (I use the keychain package to make authenticated keys useable in scripts; it just sources a few environment variables to identify the ssh agent fifo, etc..) If you do that, then your code might be changed to ... foreach $createdirectories(@createdirectories) { system "ssh $line sudo mkdir " . "$HOMEDIR/$createme/incoming/$directory" . "$HOMEDIR/$createme/pub/$directory"; } I don't see any password checking for sudo, which I find confusing. Presumably you've already connected to each host to authenticate sudo. Ken -- Ken Irving |