Ensure that a known hosts file gets created if it does not exist
@@ -15,6 +15,15 @@ import (
// InteractiveHostKeyCallback verifying the host key against known_hosts and adding the key if
// the user replies accordingly.
func InteractiveHostKeyCallback(knownHostsFilePath string) (ssh.HostKeyCallback, error) {
+ if _, err := os.Stat(knownHostsFilePath); os.IsNotExist(err) {
+ f, err := os.Create(knownHostsFilePath)
+ if err != nil {
+ return nil, fmt.Errorf("failed creating known hosts file %q: %v", knownHostsFilePath, err)
+ }
+ _ = f.Close()
+ } else if err != nil {
+ return nil, fmt.Errorf("failed reading known host file %q: %v", knownHostsFilePath, err)
+ }
validator, err := knownhosts.New(knownHostsFilePath)
if err != nil {
return nil, err
