I have a script that should list all files in an SFTP server and output that in a file (to be used by another script). The cmd that produces the needed output is:
echo ls | psftp -l myusername -pw mycomplexpwd FTPServerHostname > C:/Users/myuser/Desktop/ls.txt
and this would be invoked by Windows Task Scheduler couple of times a day. For some reason, when scheduling this command (in a .bat file) and running via user SYSTEM, the output file would only contain this:
Remote working directory is /
psftp> quit
While when using another user, the output is as expected (listing of all files) -see https://serverfault.com/questions/1084015/why-psftp-script-is-failing-when-ran-as-system.
I need a way to script that and be able to run it as SYSTEM like the rest of my scripts in that system. I've also tried the below:
psftp -l myusername -pw mycomplexpwd FTPServerHostname < C:/Users/myuser/Desktop/lscmd.txt > C:/Users/myuser/Desktop/ls.txt
and:
psftp -l myusername -pw mycomplexpwd FTPServerHostname -b C:/Users/myuser/Desktop/lscmd.txt > C:/Users/myuser/Desktop/ls.txt
where lscmd.txt contains the below:
ls
And the behavior is the same. EDIT: as indicated by Martin below, the below might've not generated the same output but rather not touched the file. Didn't generate the expected results however.
Anything I can do so I can do the needed behavior?
OS is Windows Server 2012 R2.
So turns out there is an added step of trusting the sFTP server in the first connection (or adding the key to
HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys). Check the related serverfault question for (slightly) more details of how I did it. Both theecho ls | psftp -l myusername -pw mycomplexpwd FTPServerHostname > C:/Users/myuser/Desktop/ls.txtand the other variants (e.g.-b) worked afterwards.EDIT: I believe my biggest problem was getting cmd as
SYSTEMso I can debug what is happening, once I could (see the sister serverfault question for how I did it) it became clear to me. For reference and better clarity (since I got downvoted without explanation!), below is the output of the command before adding the key, just masked the sensitive parts, showing that I did getRemote working directory is /message that was in the output file: