WinSCP – Host ssh-rsa Key Refused in Scheduled Task but Not Manually

rsascheduled-tasksftpwindowswinscp

As part of a scheduled task that runs on a Windows Server 2012 machine, I use WinSCP to connect via sFTP using credentials and ssh-rsa key. When the scheduled task runs, the connection fails with the following error message:

2019/08/26 05:27:28 - Push files to sFTP - (stdout) Authenticating...
2019/08/26 05:27:28 - Push files to sFTP - (stdout) Host key does not match configured key "ps8Qj1+Y5WmEKcjdH05cqfzOGCxXHa+X3lhCixestv8="!
2019/08/26 05:27:28 - Push files to sFTP - (stdout) Host key fingerprint is ssh-rsa 2048 ps8Qj1+Y5WmEKcjdH05cqfzOGCxXHa+X3lhCixestv8=.
2019/08/26 05:27:28 - Push files to sFTP - (stdout) 
2019/08/26 05:27:28 - Push files to sFTP - (stdout) Authentication failed.

As you can see, the ssh-rsa key is the same in both cases.
And if I run the task manually from the Task Scheduler, execute the batch file that the scheduled task calls upon, or if I manually connect to the sFTP server using WinSCP with the same configuration, the connection is successful.

This is the connection string (server details edited):

"c:\Program Files (x86)\WinSCP\WinSCP.com" /command "open sftp://user:pwd@secure-transfer-ftp.server.com -passive=on -timeout=500 -hostkey=ps8Qj1+Y5WmEKcjdH05cqfzOGCxXHa+X3lhCixestv8=" 

Any idea why it fails when it runs as scheduled task?
The only change has been an update on the SFTP address, as the other party has updated their IPs and associated URLs, but according to the, the key has not changed (as shown by the fact that I can connect manually)

Best Answer

Your script is wrong. The -hostkey switch must include even the key type and key size (only an upcoming WinSCP 5.16 will allow checksum only, but it will discouraged anyway).

So it should be:

"...\WinSCP.com" /command "open ... -hostkey=""ssh-rsa 2048 ps8Qj1+Y5WmEKcjdH05cqfzOGCxXHa+X3lhCixestv8="""

The reason why it works in other environments is most probably that the host key is cached in Windows registry of the account that you use for the tests. So the value from the script is not even considered. While the account that runs your Task Scheduler job does not have the key cached.

This is covered in WinSCP FAQ My script works fine when executed manually, but fails or hangs when run by Windows Scheduler, SSIS or other automation service. What am I doing wrong?