A former National Security Agency contractor was sentenced Friday to nine years in prison after pleading guilty earlier this year to removing classified information from the spy agency, in what is widely viewed as one of the largest thefts of U.S. government secrets in history.

Harold “Hal” Martin III, who was indicted in 2017 and accused of taking home thousands of pages of documents containing some of the nation’s most sensitive secrets over a span of several years, pleaded guilty in March to a single count of willful retention of national defense information. Prosecutors at the time agreed to recommend dropping 19 other counts of the same charge, and a plea deal recommended a nine-year sentence.

“Harold Martin was entrusted with some of the nation’s most sensitive information,” John Demers, the assistant attorney general for national security, said in a statement. “Instead of respecting the trust given to him by the American people, Martin violated that trust and put our nation’s security at risk.”

Following his prison term, Mr. Martin will be under three years of supervised release, a spokeswoman for the U.S. attorney’s office in Maryland said. A lawyer for Mr. Martin declined to comment.

Mr. Martin, a Navy veteran, spent up to two decades as a contractor stealing sensitive national defense information from multiple government intelligence agencies by simply walking out of buildings with stolen material. He avoided detection for an unusually long time as he stockpiled an enormous trove of files in his suburban Maryland home, shed and car, according to prosecutors.