fix: sovle the problem that the host isn't unique and store repeat host

This commit is contained in:
Levi Yan
2024-10-23 12:38:55 +08:00
parent 4c3233dbcc
commit 4ded936bf7

View File

@@ -108,29 +108,23 @@ export default class RemoteContainer {
// check if the host and related info exist in local ssh config file before saving // check if the host and related info exist in local ssh config file before saving
var canAppendSSHConfig = true var canAppendSSHConfig = true
if (fs.existsSync(sshConfigPath)) { if (fs.existsSync(sshConfigPath)) {
var hasHost = false;
var hasPort = false;
var reader = rd.createInterface(fs.createReadStream(sshConfigPath)) var reader = rd.createInterface(fs.createReadStream(sshConfigPath))
reader.on("line", (l:string) => {
if (l.includes(`HostName ${host}`)) {
hasHost = true
}
if (l.includes(`Port ${port}`)) { for await (const line of reader) {
hasPort = true // host format: hostname:port
if (line.includes(`Host ${host}:${port}`)) {
// the container ssh info exists
canAppendSSHConfig = false
break;
} }
})
if (hasHost && hasPort) {
// the container ssh info exists
canAppendSSHConfig = false
} }
} }
if (canAppendSSHConfig) { if (canAppendSSHConfig) {
// save the host to the local ssh config file // save the host to the local ssh config file
const hostInConfig = `${host}:${port}` // host format: hostname:port
const newSShConfigContent = const newSShConfigContent =
`\nHost ${host}\n HostName ${host}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ~/.ssh/id_rsa\n `; `\nHost ${hostInConfig}\n HostName ${host}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ~/.ssh/id_rsa\n `;
fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' }); fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' });
console.log('Host registered in local ssh config'); console.log('Host registered in local ssh config');
} }