private void SaveAccountsToWindowsCredentialManager() { var credentialsQuery = this.Accounts.Select(a => new Credential { Target = string.Format("{0}.{1}:{2}", CredentialsStore_TargetPrefix, a.Type, a.Name), Username = a.Id, Password = a.Secret, PersistanceType = PersistanceType.LocalComputer, Type = CredentialType.Generic, Description = a.AdditionalSettings != null ? JsonConvert.SerializeObject(a.AdditionalSettings) : null }); var credentials = credentialsQuery.ToArray(); // Save changed credentials to Credential Store foreach (var credential in credentials) { credential.Save(); } // Remove deleted credentials from Credential Store var credentialSet = new CredentialSet(); credentialSet.Load(); var credentialsToDelete = credentialSet.FindAll(toDelete => toDelete.Target.StartsWith(CredentialsStore_TargetPrefix) && credentials.All(_ => toDelete.Target != _.Target)); foreach (var credential in credentialsToDelete) { credential.Delete(); } }
static void Main(string[] args) { SqlConnection conn = new SqlConnection("Server=localhost;Database=trial;Integrated Security=true;"); conn.Open(); Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1000000; i++) { CredentialSet cred = new CredentialSet { LastUpdate = DateTime.Now, Title = string.Format("Joe's cred {0}", i), Notes = string.Format("Joe's note {0}", i) }; WriteCredential_StoredProcedure(cred, conn); } watch.Stop(); conn.Close(); Console.WriteLine(string.Format("Elapsed time: {0}", watch.Elapsed)); Console.Read(); }
private void Context_Delete(object sender, RoutedEventArgs e) { var menuItem = (MenuItem) sender; //Get the ContextMenu to which the menuItem belongs var contextMenu = (ContextMenu) menuItem.Parent; //Find the placementTarget var item = (DataGrid) contextMenu.PlacementTarget; if (item.SelectedCells == null || item.SelectedCells.Count == 0) { return; } var modelView = (CredentialModelView) CredentialsGrid.DataContext; var set = new CredentialSet(); set.Load(); foreach (DataGridCellInfo selectedcell in item.SelectedCells) { var credential = selectedcell.Item as CustomCredentialItem; if (credential == null) continue; List<Credential> userCredentials = set.FindAll(setItem => modelView.User.Username == setItem.Username); Credential foundtoDelete = userCredentials.Find(credential.IsSame); foundtoDelete.Delete(); } modelView.RefreshUsers(); }
public void CredentialSet_Load_ShouldReturn_Self() { CredentialSet set = new CredentialSet(); set.Load().ShouldBeOfType(typeof (CredentialSet)); set.Dispose(); }
public string generatePLMKeyFromStructuredContext(string iAdminKey, CredentialSet iCredentialSet) { generatePLMKeyFromStructuredContextRequest inValue = new generatePLMKeyFromStructuredContextRequest(); inValue.iAdminKey = iAdminKey; inValue.iCredentialSet = iCredentialSet; generatePLMKeyFromStructuredContextResponse retVal = ((IPLMKeyManagement)(this)).generatePLMKeyFromStructuredContext(inValue); return(retVal.oPLMKey); }
public void CredentialSetLoadShouldReturnSelf() { RunIfWrapper.RunIfWindows(() => { CredentialSet set = new CredentialSet(); Assert.IsType <CredentialSet>(set.Load()); set.Dispose(); }); }
private void UpdateFromControls(CredentialSet toUpdate) { toUpdate.Domain = this.txtDomain.Text; toUpdate.Name = this.txtName.Text; toUpdate.Username = this.txtUserName.Text; if (this.txtPassword.Text != CredentialPanel.HIDDEN_PASSWORD) { toUpdate.SecretKey = this.txtPassword.Text; } }
public async Task AutoFillServerSettingsAsync(OptionsModel optionsModel) { CredentialSet credentials = await new SwisscomOauth().GetCredentialsAsync(optionsModel.CalenderUrl); if (credentials != null) { optionsModel.UserName = credentials.Username; optionsModel.Password = SecureStringUtility.ToSecureString(credentials.Password); optionsModel.CalenderUrl = credentials.Url; } }
private void okButton_Click(object sender, EventArgs e) { this.set = new CredentialSet { Name = "", Username = this.userTextBox.Text, SecretKey = this.passwordTextBox.Text, Domain = this.domainTextBox.Text }; this.Close(); }
/// <summary> /// Get a password for a particular host and username. Throw if it isn't there. /// </summary> /// <param name="host"></param> /// <param name="username"></param> /// <returns></returns> public static string FetchPassword(string host, string username) { var cs = new CredentialSet(host); var thePasswordInfo = cs.Load().Where(c => c.Username == username).FirstOrDefault(); if (thePasswordInfo == null) { throw new ArgumentException("Must enter password"); } return thePasswordInfo.Password; }
/// <summary> /// Fetch from GRID the credential name. /// </summary> /// <param name="job"></param> /// <param name="origDSName"></param> /// <returns></returns> public static string ResultingDataSetName(this AtlasJob job, string origDSName, int jobIteration = 0) { using (var credList = new CredentialSet("GRID")) { var gridCredentials = credList.Load().FirstOrDefault(); if (gridCredentials == null) { throw new ArgumentException("Please create a generic windows credential with the target 'GRID' with the user name as the rucio grid user name and the password to be used with voms proxy init"); } return(job.ResultingDataSetName(origDSName, gridCredentials, jobIteration)); } }
private ICredentialSet SetupCredential() { var credential = new CredentialSet(); var guardedSec = new GuardedCredential(credential, this.persistenceMock.Object.Security); guardedSec.Password = PASSWORD; var credentials = new Mock <ICredentials>(); credentials.Setup(cr => cr[It.IsAny <Guid>()]).Returns(credential); this.persistenceMock.SetupGet(p => p.Credentials).Returns(credentials.Object); return(credential); }
public bool Delete() { using (CredentialSet credentialSet = new CredentialSet(TheProduct.CredentialsTarget)) { Credential cred = credentialSet.Load().FirstOrDefault(); if (cred != null) OnChanged(); return cred != null && cred.Delete(); } }
/// <summary> /// Get a password for a particular host and username. Throw if it isn't there. /// </summary> /// <param name="host"></param> /// <param name="username"></param> /// <returns></returns> public static string FetchPassword(string host, string username) { var cs = new CredentialSet(host); var thePasswordInfo = cs.Load().Where(c => c.Username == username).FirstOrDefault(); if (thePasswordInfo == null) { throw new ArgumentException("Must enter password"); } return(thePasswordInfo.Password); }
private void UpdateOldOrCreateNew(CredentialSet oldItem) { if (oldItem == null || this.editedCredentialName != this.txtName.Text) { CredentialSet newCredential = this.CreateNewCredential(); StoredCredentials.Add(newCredential); } else { this.UpdateFromControls(oldItem); } }
/// <summary> /// We will run the job submission. We assume that any checking has already gone one /// and we are just going to execute all the commands required of this job request. /// Assume setupATLAS and rucio and voms proxy init have all been done before /// this guy is called! /// </summary> /// <param name="connection"></param> /// <param name="job"></param> /// <param name="datasetToStartWith"></param> /// <param name="credSet">Set of credentials to load. Default to CERN</param> /// <returns></returns> public static async Task <ISSHConnection> SubmitJobAsync(this ISSHConnection connection, AtlasJob job, string inputDataSet, string resultingDataSet, Action <string> statusUpdate = null, Func <bool> failNow = null, bool sameJobAsLastTime = false, string credSet = "CERN", bool dumpOnly = false) { // Get the status update protected. Action <string> update = statusUpdate != null ? statusUpdate : s => { }; // Figure out the proper submit command. string submitCmd = (job.SubmitPatternCommands.Length > 0 ? MatchSubmitPattern(job.SubmitPatternCommands, inputDataSet) : job.SubmitCommand.SubmitCommand.CommandLine) .Replace("*INPUTDS*", "{0}") .Replace("*OUTPUTDS*", "{1}"); var cernCred = new CredentialSet(credSet) .Load() .FirstOrDefault() .ThrowIfNull(() => new GRIDSubmitException($"Please create a windows generic credential with a target of '{credSet}' to allow access to kinit")); // If this is the first time through with a single job, then setup a directory we can use. if (!sameJobAsLastTime) { var linuxLocation = string.Format("/tmp/{0}", resultingDataSet); await connection.Apply(() => update("Removing old build directory")) .ExecuteLinuxCommandAsync("rm -rf " + linuxLocation, dumpOnly: dumpOnly); await connection .Apply(() => update("Setting up panda")) .ExecuteLinuxCommandAsync("lsetup panda", dumpOnly: dumpOnly); await connection.Apply(() => update("Setting up release")) .SetupRcReleaseAsync(linuxLocation, job.Release.Name, dumpOnly: dumpOnly); await connection.Apply(() => update("Getting CERN credentials")) .KinitAsync(cernCred.Username, cernCred.Password, dumpOnly: dumpOnly); await connection .ApplyAsync(job.Packages, (c, j) => c.Apply(() => update("Checking out package " + j.Name)).CheckoutPackageAsync(j.Name, j.SCTag, failNow: failNow, dumpOnly: dumpOnly)); await connection .ApplyAsync(job.Commands, (co, cm) => co.Apply(() => update("Running command " + cm.CommandLine)).ExecuteLinuxCommandAsync(cm.CommandLine, failNow: failNow, dumpOnly: dumpOnly)); await connection .Apply(() => update("Compiling release")) .BuildWorkAreaAsync(failNow: failNow, dumpOnly: dumpOnly); } // We should now be in the directory where everything is - so submit! return(await connection .Apply(() => update($"Running submit command ({inputDataSet})")) .ExecuteLinuxCommandAsync(string.Format(submitCmd, inputDataSet, resultingDataSet), failNow: failNow, dumpOnly: dumpOnly)); }
private void WindowsCredentialCollection(List <string> targets) { CurrentCredentials = new CredentialSet(); foreach (var target in targets) { Credential credential = new Credential { Target = target }; credential.Load(); CurrentCredentials.Add(credential); } }
private bool UpdateCredential() { CredentialSet conflicting = StoredCredentials.GetByName(this.txtName.Text); CredentialSet oldItem = StoredCredentials.GetByName(this.editedCredentialName); if (conflicting != null && this.editedCredentialName != this.txtName.Text) { return(this.UpdateConflicting(conflicting, oldItem)); } this.UpdateOldOrCreateNew(oldItem); return(true); }
private void CreateCredentialInPersistence() { // because of internal usage in Favorite we have to reference the singleton var persistence = this.Persistence; var credential = new CredentialSet(); var guarded = new GuardedCredential(credential, this.Persistence.Security); credential.Name = CREDENTIAL_NAME; guarded.Password = EXPECTEDPASSWORD; guarded.Domain = EXPECTED_DOMAIN; guarded.UserName = EXPECTED_USER; persistence.Credentials.Add(credential); }
public static void SaveRconPass(string pass) { Credential c = new Credential() { Username = "******", Password = pass, Target = "rocketrcon" }; c.Save(); CredentialSet a = new CredentialSet(target: "rocketrcon"); }
private Button CreateSaveButton(Control parent) { var b = new Button { Text = "Save" }; b.Click += (sender, args) => { if (FilterCollection.Count > 1) { var result = PasswordInputBox.GetPassword(parent, "Master Password"); if (!string.IsNullOrEmpty(result)) { using (var password = new SecureStringOrArray(Encoding.ASCII.GetBytes(result))) { var folderBasedFilePathProvider = new FolderBasedFilePathProvider("."); var localSecureFileRepository = new LocalSecureFileRepository(folderBasedFilePathProvider, "muipw.iv", DataFileName, "muipw.ver", "muipw.salt"); var aesFormatter = new AesFormatter(localSecureFileRepository); try { //just test that the password is correct by deserializing the current data. var credentialSet = aesFormatter.DeserializeData <CredentialSet>(password); _secretKeyProvider.Initialize(credentialSet.Credentials); _secretKeyProvider.Initialize(FilterCollection); var mSecretsSecretKey = _secretKeyProvider.GetSecret(SecretKeyConstants.MSecretsSecretKeyName); if (mSecretsSecretKey == null) { MessageBox.Show($"Missing {SecretKeyConstants.MSecretsSecretKeyName}!"); return; } var fileBroker2 = SecureFileBroker.Create(folderBasedFilePathProvider, mSecretsSecretKey, "muipw.iv", DataFileName, "muipw.ver", "muipw.salt"); aesFormatter = new AesFormatter(fileBroker2); var set = new CredentialSet(); foreach (var credential in FilterCollection) { set.Credentials.Add(credential); } aesFormatter.SerializeData(password, set); } catch (Exception) { MessageBox.Show("Incorrect password!"); } } } } }; return(b); }
public bool Delete() { using (CredentialSet credentialSet = new CredentialSet(TheProduct.CredentialsTarget)) { Credential cred = credentialSet.Load().FirstOrDefault(); if (cred != null) { OnChanged(); } return(cred != null && cred.Delete()); } }
public override ICredentials[] GetCredentials(Uri uri) { if (null == uri) { throw new ArgumentNullException("uri"); } using (CredentialSet set = new CredentialSet(uri.Host)) { if (null == set || set.Count < 1) { return new ICredentials[0] { }; } return set .Select(cred => new NetworkCredential(cred.UserName, cred.Password)) .ToArray(); } }
static void Main(string[] args) { CredentialSet set = new CredentialSet(); var creds = set.Load(); foreach (Credential cred in creds) { Console.WriteLine(cred.Target); if (cred.Target.Contains("MS.Outlook")) { cred.Delete(); } } }
private void CredentialDropdown_SelectedIndexChanged(object sender, EventArgs e) { this.CredentialsPanel.Enabled = true; CredentialSet set = (this.CredentialDropdown.SelectedItem as CredentialSet); if (set != null) { this.CredentialsPanel.Enabled = false; this.cmbDomains.Text = set.Domain; this.cmbUsers.Text = set.Username; this.txtPassword.Text = set.SecretKey; this.chkSavePassword.Checked = true; } }
private void FillControlsFromCredential(CredentialSet editedCredential) { if (editedCredential != null) { this.txtName.Text = editedCredential.Name; this.txtDomain.Text = editedCredential.Domain; this.txtUserName.Text = editedCredential.Username; if (!string.IsNullOrEmpty(editedCredential.Password)) { this.txtPassword.Text = CredentialPanel.HIDDEN_PASSWORD; } this.editedCredentialName = editedCredential.Name; } }
public void CredentialSet_Load_With_TargetFilter() { Credential credential = new Credential { Username = "******", Password = "******", Target = "filtertarget" }; credential.Save(); CredentialSet set = new CredentialSet("filtertarget"); set.Load().ShouldHaveCountOf(1); set.Dispose(); }
public static bool WriteCredential(CredentialSet cred, SqlConnection conn) { using (SqlDataAdapter da = new SqlDataAdapter()) { da.InsertCommand = new SqlCommand("insert into Credentials1 (Notes, Title) values (@note, @title)",conn); da.InsertCommand.Parameters.Add(new SqlParameter("@note", SqlDbType.VarChar)); da.InsertCommand.Parameters.Add(new SqlParameter("@title", SqlDbType.VarChar)); da.InsertCommand.Parameters["@note"].Value = cred.Notes; da.InsertCommand.Parameters["@title"].Value = cred.Title; da.InsertCommand.ExecuteNonQuery(); } return true; }
public bool TryReadCred(out SscLogin login) { using (CredentialSet credentialSet = new CredentialSet(TheProduct.CredentialsTarget)) { Credential credential = credentialSet.Load().SingleOrDefault(); if (credential != null) { login = new SscLogin(credential.Username, credential.Password); return true; } login = null; return false; } }
public ManageCredentialForm(CredentialSet editedCredential) { this.InitializeComponent(); this.FillControlsFromCredential(editedCredential); this.Text = AssemblyInfo.Title + " - " + "Credential manager"; this.txtPassword.PasswordChar = CredentialPanel.HIDDEN_PASSWORD_CHAR; if (Terminals.Configuration.Files.Main.Settings.Settings.CredentialStore == Terminals.Configuration.Files.Main.CredentialStoreType.KeePass) { SaveButton_cred.Enabled = false; } }
public void CredentialSet_Load_With_TargetFilter() { var credential = new Credential { Username = "******", Password = "******", Target = "filtertarget" }; credential.Save(); var set = new CredentialSet("filtertarget"); var credentialSet = set.Load(); Assert.Single(credentialSet); }
public static bool WriteCredential_StoredProcedure(CredentialSet cred, SqlConnection conn) { using (SqlDataAdapter da = new SqlDataAdapter()) { da.InsertCommand = new SqlCommand("Insert_Credential", conn); da.InsertCommand.CommandType = CommandType.StoredProcedure; da.InsertCommand.Parameters.Add(new SqlParameter("@notes", SqlDbType.VarChar)); da.InsertCommand.Parameters.Add(new SqlParameter("@title", SqlDbType.VarChar)); da.InsertCommand.Parameters["@notes"].Value = cred.Notes; da.InsertCommand.Parameters["@title"].Value = cred.Title; da.InsertCommand.ExecuteNonQuery(); } return true; }
private void LoadAccountsFromWindowsCredentialManager() { var credentialSet = new CredentialSet(); credentialSet.Load(); var credentials = credentialSet.FindAll(c => c.Target.StartsWith(CredentialsStore_TargetPrefix)); var accountsQuery = credentials.Select(c => new AccountConfiguration { Type = (StorageType)Enum.Parse(typeof(StorageType), c.Target.Substring(c.Target.IndexOf('.') + 1, (c.Target.IndexOf(':') - c.Target.IndexOf('.') - 1))), Name = c.Target.Substring(c.Target.IndexOf(':') + 1), Id = c.Username, Secret = c.Password, }); this.Accounts = accountsQuery.ToList(); }
private void SaveObject(PasswordBox parameter) { if (parameter.SecurePassword.Length == 0) { return; } var set = new CredentialSet(); set.Load(); foreach (Credential item in User.GetCredentials(set)) { item.SecurePassword = parameter.SecurePassword; item.Save(); } RefreshUsers(); }
public bool TryReadCred(out SscLogin login) { using (CredentialSet credentialSet = new CredentialSet(TheProduct.CredentialsTarget)) { Credential credential = credentialSet.Load().SingleOrDefault(); if (credential != null) { login = new SscLogin(credential.Username, credential.Password); return(true); } login = null; return(false); } }
public static void GetProxyCredentials(string proxiedHost) { CredentialSet set = new CredentialSet(); set.Load(); if (set.Count > 0) { Credential[] credentialList = set.ToArray(); foreach (Credential c in credentialList) { //if (c.Target == proxyHost) if (c.Type == CredentialType.Generic && c.Target == proxiedHost) //if (c.Type == CredentialType.Generic ) { Console.WriteLine("Target: " + c.Target); Console.WriteLine("Username: "******"Password is ok"); } else { Console.WriteLine("---No Password"); } Console.WriteLine("Type: " + c.Type); Console.WriteLine("generic credentials found"); Console.WriteLine(""); proxyCredential.Username = c.Username; proxyCredential.Password = c.Password; proxyCredential.Target = c.Target; proxyCredential.Type = c.Type; } else { //just a placeholder } } } else { Console.WriteLine("You are not athenticated yet."); Console.Read(); } }
public void ReadBack() { var info = util.GetUsernameAndPassword(); var sclist = new CredentialSet(info.Item1); var passwordInfo = sclist.Load().Where(c => c.Username == info.Item2).FirstOrDefault(); if (passwordInfo == null) { throw new ArgumentException(string.Format("Please create a generic windows credential with '{0}' as the target address, '{1}' as the username, and the password for remote SSH access to that machine.", info.Item1, info.Item2)); } // Create the connection, but do it lazy so we don't do anything if we aren't used. var host = info.Item1; var username = info.Item2; var password = passwordInfo.Password; // Do the work. var con = new SshClient(host, username, password); con.Connect(); var s = con.CreateShellStream("Commands", 240, 200, 132, 80, 1024); var reader = new StreamReader(s); var writer = new StreamWriter(s); writer.AutoFlush = true; // Do the read command writer.WriteLine("read -p \"hi there: \" bogus"); Thread.Sleep(200); writer.Write("Life Is Great\n"); Thread.Sleep(200); writer.WriteLine("set | grep bogus"); Thread.Sleep(200); string l = ""; while ((l = reader.ReadLine()) != null) { Console.WriteLine(l); } Assert.Inconclusive(); }
public void CredentialSetLoadWithTargetFilter() { TestUtils.RunIfWindows(() => { Win32Credential credential = new Win32Credential { Username = "******", Password = "******", Target = "filtertarget" }; credential.Save(); CredentialSet set = new CredentialSet("filtertarget"); Assert.Equal(1, set.Load().Count); set.Dispose(); }); }
public void CredentialSet_Load_With_TargetFilter() { Credential credential = new Credential { Username = "******", Password = "******", Target = "filtertarget" }; credential.Save(); CredentialSet set = new CredentialSet("filtertarget"); var result = set.Load(); Assert.AreEqual(result.Count, 1); set.Dispose(); }
public void CredentialSetLoadWithTargetFilter() { RunIfWrapper.RunIfWindows(() => { Win32Credential credential = new Win32Credential { Username = "******", Password = Guid.NewGuid().ToString(), Target = "filtertarget" }; credential.Save(); CredentialSet set = new CredentialSet("filtertarget"); Assert.Equal(1, set.Load().Count); set.Dispose(); }); }
/// <summary> /// Gets the credentials for the current target name. /// </summary> /// <param name="targetName">The target name to filter by.</param> /// <returns>The list of credentials for the target name filter.</returns> public List <Credential> GetCredentials(string targetName) { List <Credential> col = new List <Credential>(); // Create a new credential set for the target name. using (CredentialSet credentials = new CredentialSet(targetName)) { // For each target name found. foreach (Credential credential in credentials) { col.Add(credential); } } // Return the collection of credentials. return(col); }
private void LoadAccountsFromWindowsCredentialManager() { var credentialSet = new CredentialSet(); credentialSet.Load(); var credentials = credentialSet.FindAll(c => c.Target.StartsWith(CredentialsStore_TargetPrefix)); StorageType type; var filterQuery = credentials.Where(c => Enum.TryParse(GetCredentialTypeAsString(c), out type)); var accountsQuery = filterQuery.Select(c => new AccountConfiguration { Type = (StorageType)Enum.Parse(typeof(StorageType), GetCredentialTypeAsString(c)), Name = c.Target.Substring(c.Target.IndexOf(':') + 1), Id = c.Username, Secret = c.Password, AdditionalSettings = !string.IsNullOrEmpty(c.Description) ? JsonConvert.DeserializeObject<Dictionary<string, string>>(c.Description) : null }); this.Accounts = accountsQuery.ToList(); }
public void CredentialSet_Load() { Credential credential = new Credential { Username = "******", Password = "******", Target = "target", Type = CredentialType.Generic }; credential.Save(); CredentialSet set = new CredentialSet(); set.Load(); set.ShouldNotBeNull(); set.ShouldNotBeEmpty(); credential.Delete(); set.Dispose(); }
public FavsList() { // This prevents SharpDevelop and Visual Studio from both an exception in design mode for controls using this HistoryTreeView and from crashing when opening the // designer for this class. if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { this.InitializeComponent(); CredSet = new CredentialSet(); // Update the old treeview theme to the new theme from Win Vista and up WindowsApi.SetWindowTheme(this.favsTree.Handle, "Explorer", null); WindowsApi.SetWindowTheme(this.dbTreeView1.Handle, "Explorer", null); WindowsApi.SetWindowTheme(this.historyTreeView.Handle, "Explorer", null); this.historyTreeView.DoubleClick += this.HistoryTreeView_DoubleClick; this.LoadFavorites(); this.LoadState(); } }
public SSHConnection(string host, string username) { // Fetch the username and password. var sclist = new CredentialSet(host); var passwordInfo = sclist.Load().Where(c => c.Username == username).FirstOrDefault(); if (passwordInfo == null) { throw new ArgumentException(string.Format("Please create a generic windows credential with '{0}' as the target address, '{1}' as the username, and the password for remote SSH access to that machine.", host, username)); } // Create the connection, but do it lazy so we don't do anything if we aren't used. _client = new Lazy<SshClient>(() => { var c = new SshClient(host, username, passwordInfo.Password); c.Connect(); return c; }); // Create the scp client for copying things _scp = new Lazy<ScpClient>(() => { var c = new ScpClient(host, username, passwordInfo.Password); c.Connect(); c.ErrorOccurred += (sender, error) => _scpError = error.Exception; return c; }); // And create a shell stream. Initialize to find the prompt so we can figure out, later, when // a task has finished. _shell = new Lazy<ShellStream>(() => { var s = _client.Value.CreateShellStream("Commands", TerminalWidth, 200, 132, 80, 240 * 200); s.WaitTillPromptText(); s.WriteLine("# this initialization"); DumpTillFind(s, "# this initialization"); s.ReadLine(); // Get past the "new-line" that is at the end of the printed comment above _prompt = s.ReadRemainingText(100); Trace.WriteLine("Initialization: prompt=" + _prompt, "SSHConnection"); return s; }); }
public void Connect(String connectionName, Boolean forceConsole, Boolean forceNewWindow, bool isDatabaseFavorite, CredentialSet credential = null, bool waitForEnd = false) { Log.InsideMethod(); FavoriteConfigurationElement favorite = FavoritesFactory.GetFavoriteUpdatedCopy(connectionName, forceConsole, forceNewWindow, credential, isDatabaseFavorite); if (favorite != null) { ConnectionHistory.Instance.RecordHistoryItem(connectionName); this.SendNativeMessageToFocus(); this.CreateTerminalTab(favorite, waitForEnd); } else this.CreateNewTerminal(waitForEnd, connectionName); }
/// <summary> /// Initializes the VOMS proxy for use on the GRID. The connection must have already been configured so that /// the command voms-proxy-init works. /// </summary> /// <param name="connection">The configured SSH shell</param> /// <param name="GRIDUsername">The username to use to fetch the password for the voms proxy file</param> /// <param name="voms">The name of the voms to connect to</param> /// <returns>Connection on which the grid is setup and ready to go</returns> public static ISSHConnection VomsProxyInit(this ISSHConnection connection, string voms, Func<bool> failNow = null, bool dumpOnly = false) { // Get the GRID VOMS password var sclist = new CredentialSet("GRID"); var passwordInfo = sclist.Load().FirstOrDefault(); if (passwordInfo == null) { throw new ArgumentException("There is no generic windows credential targeting the network address 'GRID' for username. This password should be your cert pass phrase and your on-the-grid username. Please create one on this machine."); } // Run the command bool goodProxy = false; var whatHappened = new List<string>(); connection .ExecuteCommand(string.Format("echo {0} | voms-proxy-init -voms {1}", passwordInfo.Password, voms), l => { goodProxy = goodProxy || l.Contains("Your proxy is valid"); whatHappened.Add(l); }, secondsTimeout: 20, failNow: failNow, dumpOnly: dumpOnly ); // If we failed to get the proxy, then build an error message that can be understood. Since this // could be for a large range of reasons, we are going to pass back a lot of info to the user // so they can figure it out (not likely a program will be able to sort this out). if (goodProxy == false && !dumpOnly) { var error = new StringBuilder(); error.AppendLine("Failed to get the proxy: "); foreach (var l in whatHappened) { error.AppendLine(string.Format(" -> {0}", l)); } throw new ArgumentException(error.ToString()); } return connection; }
public static int Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Usage: [mono] Lassie.exe <user>/<repo> <file> <branch|commit|tag> <out_file>"); Console.Write("Lassie {0}", Properties.Resources.Version); Console.WriteLine(@" (\ (\_\_^__o ___ `-'/ `_/ '`--\______/ | ' / | ` . ' `-`/.------'\^-' mic"); return 3; } // get args string repo = args[0]; string path = args[1]; string commitish = args[2]; string outFilename = args[3]; // check platform Platform platform = WhichPlatform(); // check for stored credentials string token = null, user = null, pass = null; // if windows, let's try to get the username/password from the credential manager // requires the user to have setup `git config --global credential.helper wincred` if (platform == Platform.Windows) { var creds = new CredentialSet("git:*"); // wild creds.Load(); var credential = creds.FirstOrDefault(c => c.Target.EndsWith("github.com")); if (credential != null) { //Credential credential = new Credential { Target = "git:https://<username>@github.com", Type = CredentialType.Generic }; credential.Load(); user = credential.Username; pass = credential.Password; } } // if we didn't manage to get credentials from windows' credential manager, try legacy lassie.json config file if (user == null || pass == null) { string configFile = WhereConfig(platform); if (File.Exists(configFile)) { var config = JsonConvert.DeserializeObject<Config>(File.ReadAllText(configFile)); token = config.Token; // TODO: reset if >month since last updated } else { Console.Error.WriteLine("Couldn't find any github credentials on your system. Looks like Timmy's spending the night in the well."); return 5; } } // now it begins string contents; try { // fetch the file contents if (token != null) { contents = Fetch(repo, path, commitish, token); } else { contents = Fetch(repo, path, commitish, user, pass); } // normalise line endings for windows if (platform == Platform.Windows) { string normalised = Regex.Replace(contents, @"\r\n|\n\r|\n|\r", "\r\n"); contents = normalised; } // ensure full path to outFilename exists Directory.CreateDirectory(Path.GetDirectoryName(outFilename)); // write File.WriteAllText(outFilename, contents); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; string msg = string.Format("{3}: {0}/{1}@{2}.", repo, path, commitish, e.Message); if (e.InnerException != null) { msg += string.Format(" (Inner Exception = '{0}'", e.InnerException.Message); } Console.Error.WriteLine(msg); Console.ResetColor(); return 1; } Console.WriteLine("Contents of {0}/{1}@{2} successfully written to {3}", args); return 0; }